Coding in Visual Basic: A Beginner’s Guide to Creating Your First Console App

Are you looking to dive into the world of programming? Visual Basic (VB) is an excellent language to start with, known for its readability and beginner-friendly syntax. This tutorial will guide you through creating a simple console application using Visual Studio, a powerful Integrated Development Environment (IDE) that makes coding in Visual Basic a breeze. Whether you’re completely new to coding or looking to add VB to your skillset, this step-by-step guide will get you started.

In this tutorial, we will cover the essential steps to build your first Visual Basic console application. You will learn how to:

  • Set up a new Visual Studio project for Visual Basic.
  • Understand and run the default application.
  • Write code to take input from the user.
  • Enhance your app with a simple number addition feature.
  • Integrate Git source control into your project.
  • Properly clean up project resources.

Prerequisites

Before we begin, ensure you have Visual Studio installed on your system. You can download the free Community version from the official Visual Studio website. Make sure to include the .NET desktop development workload during installation, as this provides the necessary tools for Visual Basic development.

Creating Your First Visual Basic Project

Let’s start by creating a new project in Visual Studio. This project will house all the files needed for your Visual Basic console application.

  1. Launch Visual Studio.

  2. On the start window, select Create a new project.

  3. In the “Create a new project” window, filter your options. Choose Visual Basic from the language dropdown, Windows from the platform dropdown, and Console from the project types.

  4. After applying these filters, you should see the Console App template. Select it and click Next.

    If you can’t find the Console App template, a prompt “Not finding what you’re looking for?” might appear. Click on Install more tools and features.

    This will open the Visual Studio Installer. Select the .NET desktop development workload and click Modify. Follow the prompts to install the workload and then return to step 2.

  5. In the “Configure your new project” window, name your project. Type WhatIsYourName in the Project name box and click Next.

  6. In the “Additional information” window, ensure .NET 8.0 is selected as your target framework. If not, choose .NET 8.0 from the dropdown menu. Then, click Create.

    Visual Studio will now generate your new project and open it, displaying the code editor with the default Program.vb file.

Running Your Visual Basic Application

Once your project is created, Visual Studio automatically generates a Program.vb file. This file contains the basic structure of your console application, including code that displays “Hello World!” in the console.

You can run your application in two primary ways: within Visual Studio in debug mode, or as a standalone application directly from your computer.

Running in Debug Mode

Debug mode allows you to run your application within the Visual Studio environment, which is helpful for testing and finding errors in your code.

  1. Look for the WhatIsYourName button (it might also appear as a play button or your project name) in the Visual Studio toolbar, usually at the top. Click this button to start your application in debug mode. Alternatively, you can press F5.

  2. A console window will appear, displaying the output “Hello World!”. This confirms your application is running correctly. Press any key in the console window to close the application.

Running as a Standalone Application

To run your application outside of Visual Studio, as a standalone executable file, follow these steps:

  1. In the Visual Studio menu bar, click on Build and then select Build Solution. This compiles your code into an executable file.
  2. In the Solution Explorer pane (usually on the right side of Visual Studio), right-click on WhatIsYourName and select Open File in File Explorer. This will open the project folder in File Explorer.
  3. Navigate into the binDebugnet8.0 directory within your project folder. Here, you will find WhatIsYourName.exe, which is your compiled application. Double-click WhatIsYourName.exe to run it.
  4. You’ll see a console window briefly appear and then close quickly. This is because the default program executes and finishes without pausing. In the next section, we’ll add code to keep the console window open so you can see the output.

Adding Code for User Input

Let’s make our application more interactive. We’ll modify the code to ask the user for their name and then display a personalized greeting along with the current date and time. We’ll also add a pause to keep the console window open until the user presses a key.

  1. Open the Program.vb file in Visual Studio.

  2. Locate the Sub Main(args As String()) block. Replace the existing Console.WriteLine("Hello World!") line with the following Visual Basic code:

    Console.Write("Please enter your name: ")
    Dim name = Console.ReadLine()
    Dim currentDate = DateTime.Now
    Console.WriteLine($"Hello, {name}, on {currentDate:d} at {currentDate:t}")
    Console.Write("Press any key to continue...")
    Console.ReadKey(True)
  3. Run your application again, either in debug mode (F5) or as a standalone executable.

  4. When the console window appears, it will prompt you to “Please enter your name:”. Type your name and press Enter.

  5. The application will then display a greeting message including your name and the current date and time. Finally, it will display “Press any key to continue…” and wait for your input before closing.

Now, when you run the standalone .exe file, the console window will stay open until you press a key, allowing you to see the output before the application closes.

Extra Credit: Building a Simple Addition Calculator

Let’s extend our application further by adding a feature to add two numbers. This will introduce you to working with numerical input and performing basic arithmetic in Visual Basic.

  1. Modify your Program.vb code to look like this:

    Module Program
    
        Sub Main(args As String())
            Console.WriteLine("Simple Addition Calculator")
            Console.WriteLine("-------------------------")
    
            Console.Write("Enter the first number: ")
            Dim num1Input As String = Console.ReadLine()
            Dim num1 As Integer
    
            If Integer.TryParse(num1Input, num1) Then
                Console.Write("Enter the second number: ")
                Dim num2Input As String = Console.ReadLine()
                Dim num2 As Integer
    
                If Integer.TryParse(num2Input, num2) Then
                    Dim answer As Integer = num1 + num2
                    Console.WriteLine($"The sum of {num1} and {num2} is: {answer}")
                Else
                    Console.WriteLine("Invalid input for the second number. Please enter a valid integer.")
                End If
            Else
                Console.WriteLine("Invalid input for the first number. Please enter a valid integer.")
            End If
    
            Console.WriteLine("Press any key to exit...")
            Console.ReadKey(True)
    
        End Sub
    
    End Module
  2. Run the updated application. It will now function as a simple calculator, prompting you to enter two numbers and then displaying their sum. The Integer.TryParse method is used for error handling, ensuring that the program gracefully handles non-numeric input.

Incorporating Git Source Control

Version control is crucial for managing code changes, especially as projects grow. Visual Studio makes it easy to integrate Git, a popular version control system, directly into your development workflow.

  1. In the bottom-right corner of Visual Studio, you’ll see Add to Source Control. Click on this, and then select Git.

  2. The Create a Git repository dialog box will appear. You can connect to GitHub by signing in.

    Name your repository if needed (it usually defaults to your project name) and choose whether you want it to be public or private. For learning purposes, a private repository is often sufficient.

  3. Click Create and Push. This initializes a Git repository in your project folder and pushes your initial code to a remote repository on GitHub.

    Once Git is set up, you’ll see status indicators in the status bar at the bottom of Visual Studio, showing you the state of your Git repository.

Cleaning Up Resources

If you decide you no longer need the project, it’s good practice to clean up the project files.

  1. In Solution Explorer, right-click on WhatIsYourName project and select Open Folder in File Explorer.
  2. Close Visual Studio.
  3. In File Explorer, navigate two folders up from the opened project folder to the directory containing your project folder.
  4. Right-click on the WhatIsYourName folder and select Delete to remove the entire project from your system.

Further Learning

Congratulations! You have successfully created your first Visual Basic console application and learned some fundamental concepts of coding in VB and using Visual Studio.

To continue your learning journey, explore these resources:

Next Steps

Expand your knowledge by trying the next tutorial, which guides you through creating a .NET class library using Visual Studio:

Tutorial: Create a .NET class library using Visual Studio

This tutorial is just the beginning. Visual Basic, combined with Visual Studio, offers a powerful platform for building a wide range of applications. Keep practicing and exploring, and you’ll be coding more complex programs in no time!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *