Muokkaa

Jaa


Tutorial: Create a simple C# console app in Visual Studio (part 1 of 2)

In this tutorial, you use Visual Studio to create and run a C# console app, and explore some features of the Visual Studio integrated development environment (IDE). This tutorial is part 1 of a two-part tutorial series.

In this tutorial, you complete the following tasks:

  • Create a Visual Studio project.
  • Create a C# console app.
  • Debug your app.
  • Close your app.
  • Inspect your complete code.

In part 2, you extend this app to add more projects, learn debugging tricks, and reference third-party packages.

Prerequisites

You must have Visual Studio installed.

If you haven't already installed Visual Studio, go to the Visual Studio downloads page to install it for free.

Create a project

To start, create a C# application project. The project type comes with all the template files you need.

  1. Open Visual Studio, and select Create a new project in the Start window.

    Screenshot that shows the Create a new project window.

  2. In the Create a new project window, choose C# from the Language list. Next, choose Windows from the Platform list and Console from the project types list.

    After you apply the language, platform, and project type filters, choose the Console Application template, and then select Next.

    Note

    If you don't see the Console Application template, select Install more tools and features.

    Screenshot that shows the Install more tools and features link.

    In the Visual Studio Installer, select the .NET Core cross-platform development workload.

    Screenshot showing the .NET Core cross-platform development workload in the Visual Studio Installer.

    Select Modify in the Visual Studio Installer. You might be prompted to save your work. Select Continue to install the workload.

    Return to step 2 in this "Create a project" procedure.

  3. In the Configure your new project window, type or enter Calculator in the Project name box. Then, select Next.

    Screenshot that shows how to name your project 'Calculator' in the 'Configure your new project' window in Visual Studio.

  4. In the Additional information window, verify that .NET Core 3.1 appears in the Target Framework field. Then, select Create.

    Screenshot of the Additional information window in Visual Studio showing .NET Core 3.1 as the target framework for the new project.

Visual Studio opens your new project, which includes default "Hello World" code. To view it in the editor, select the code file Program.cs in the Solution Explorer window, which is typically on the right-hand side of Visual Studio.

The default "Hello World" code calls the WriteLine method to display the literal string "Hello, World!" in the console window. If you press F5, you can run the default program in Debug mode. After the application runs in the debugger, the console window stays open. Press any key to close the console window.

  1. Open Visual Studio, and select Create a new project in the Start window.

    Screenshot that shows the Create a new project window.

  2. In the Create a new project window, select All languages, and then choose C# from the dropdown list. Choose Windows from the All platforms list, and choose Console from the All project types list.

    After you apply the language, platform, and project type filters, choose the Console App template, and then select Next.

    Note

    If you don't see the Console App template, select Install more tools and features.

    Screenshot that shows the Install more tools and features link.

    In the Visual Studio Installer, select the .NET desktop development workload.

    Screenshot showing the .NET desktop development workload in the Visual Studio Installer.

    Select Modify in the Visual Studio Installer. You might be prompted to save your work. Select Continue to install the workload.

    Return to step 2 in this "Create a project" procedure.

  3. In the Configure your new project window, type or enter Calculator in the Project name box, and then select Next.

    Screenshot that shows how to name your project 'Calculator' in the 'Configure your new project' window in Visual Studio.

  4. In the Additional information window, select .NET 8.0 for the Target Framework field. Then, select Create.

    Screenshot of the Additional information window in Visual Studio showing .NET 8.0 selected as the target framework for the new project.

Visual Studio opens your new project, which includes default "Hello World" code. To view it in the editor, select the code file Program.cs in the Solution Explorer window, which is typically on the right-hand side of Visual Studio.

The single code statement calls the WriteLine method to display the literal string "Hello, World!" in the console window. If you press F5, you can run the default program in Debug mode. After the application runs in the debugger, the console window stays open. Press any key to close the console window.

Note

Starting with .NET 6, new projects using the console template generate different code than previous versions. To learn more, see the New C# templates generate top-level statements page.

Create the app

In this section, you complete the following tasks:

  • Explore some basic integer math in C#.
  • Add code to create a basic calculator app.
  • Debug the app to find and fix errors.
  • Refine the code to make it more efficient.

Explore integer math

Start with some basic integer math in C#.

  1. In the code editor, delete the default "Hello World" code.

    Screenshot that shows deleting the default Hello World code from your new calculator app.

    Specifically, delete the line that says, Console.WriteLine("Hello World!");.

  2. In its place, enter the following code:

        int a = 42;
        int b = 119;
        int c = a + b;
        Console.WriteLine(c);
        Console.ReadKey();
    

    Notice that when you enter the code, the IntelliSense feature in Visual Studio offers you the option to autocomplete the entry.

    Animation of integer math code that shows the IntelliSense autocomplete feature in the Visual Studio IDE.

  3. Select the green Start button next to Calculator to build and run your program, or press F5.

    Screenshot that shows choosing the Calculator button to run the app from the toolbar.

    A console window opens that reveals the sum of 42 + 119, which is 161.

    Screenshot that shows a console window with the results of integer math.

  4. (Optional) You can change the operator to change the result. For example, you can change the + operator in the int c = a + b; line of code to - for subtraction, * for multiplication, or / for division. Then, when you run the program, the result changes, too.

  5. Close the console window.

  1. In Solution Explorer, in the right pane, select Program.cs to display the file in the code editor

  2. In the code editor, replace the default "Hello World" code that says Console.WriteLine("Hello World!");.

    Screenshot that shows the line to replace in the program file.

    Replace the line with the following code:

        int a = 42;
        int b = 119;
        int c = a + b;
        Console.WriteLine(c);
        Console.ReadKey();
    

    If you enter the code, the Visual Studio IntelliSense feature offers you the option to autocomplete the entry.

    Animation of integer math code that shows the IntelliSense autocomplete feature in the Visual Studio IDE.

  3. To build and run your app, press F5, or select the green arrow next to the name Calculator in the top toolbar.

    Screenshot that showing selecting the Calculator button to run the app from the Debug toolbar.

    A console window opens that shows the sum of 42 + 119, which is 161.

    Screenshot of a Console window showing the results of integer math.

  4. Close the console window.

  5. Optionally, you can change the operator to change the result. For example, you can change the + operator in the int c = a + b; line of code to - for subtraction, * for multiplication, or / for division. When you run the app, the result changes accordingly.

Add code to create a calculator

Continue by adding a more complex set of calculator code to your project.

  1. In the code editor, replace all the code in Program.cs with the following new code:

        using System;
    
        namespace Calculator
        {
            class Program
            {
                static void Main(string[] args)
                {
                    // Declare variables and then initialize to zero.
                    int num1 = 0; int num2 = 0;
    
                    // Display title as the C# console calculator app.
                    Console.WriteLine("Console Calculator in C#\r");
                    Console.WriteLine("------------------------\n");
    
                    // Ask the user to type the first number.
                    Console.WriteLine("Type a number, and then press Enter");
                    num1 = Convert.ToInt32(Console.ReadLine());
    
                    // Ask the user to type the second number.
                    Console.WriteLine("Type another number, and then press Enter");
                    num2 = Convert.ToInt32(Console.ReadLine());
    
                    // Ask the user to choose an option.
                    Console.WriteLine("Choose an option from the following list:");
                    Console.WriteLine("\ta - Add");
                    Console.WriteLine("\ts - Subtract");
                    Console.WriteLine("\tm - Multiply");
                    Console.WriteLine("\td - Divide");
                    Console.Write("Your option? ");
    
                    // Use a switch statement to do the math.
                    switch (Console.ReadLine())
                    {
                        case "a":
                            Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
                            break;
                        case "s":
                            Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
                            break;
                        case "m":
                            Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
                            break;
                        case "d":
                            Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                            break;
                    }
                    // Wait for the user to respond before closing.
                    Console.Write("Press any key to close the Calculator console app...");
                    Console.ReadKey();
                }
            }
        }
    
  2. Select the Calculator button or press F5 to run your app.

    A console window opens.

  3. In the console window, follow the prompts to add the numbers 42 and 119 together.

    Your app should look similar to the following screenshot:

    Screenshot of a Console window showing the Calculator app with prompts.

  1. In the code editor, replace all the code in Program.cs with the following new code:

        // Declare variables and then initialize to zero.
        int num1 = 0; int num2 = 0;
    
        // Display title as the C# console calculator app.
        Console.WriteLine("Console Calculator in C#\r");
        Console.WriteLine("------------------------\n");
    
        // Ask the user to type the first number.
        Console.WriteLine("Type a number, and then press Enter");
        num1 = Convert.ToInt32(Console.ReadLine());
    
        // Ask the user to type the second number.
        Console.WriteLine("Type another number, and then press Enter");
        num2 = Convert.ToInt32(Console.ReadLine());
    
        // Ask the user to choose an option.
        Console.WriteLine("Choose an option from the following list:");
        Console.WriteLine("\ta - Add");
        Console.WriteLine("\ts - Subtract");
        Console.WriteLine("\tm - Multiply");
        Console.WriteLine("\td - Divide");
        Console.Write("Your option? ");
    
        // Use a switch statement to do the math.
        switch (Console.ReadLine())
        {
            case "a":
                Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
                break;
            case "s":
                Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
                break;
            case "m":
                Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
                break;
            case "d":
                Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                break;
        }
        // Wait for the user to respond before closing.
        Console.Write("Press any key to close the Calculator console app...");
        Console.ReadKey();
    
  2. Select the Calculator button or press F5 to run your app.

    A console window opens.

  3. In the console window, follow the prompts to add the numbers 42 and 119 together.

    Your app should look similar to the following screenshot:

    Screenshot of a Console window showing the Calculator app with prompts.

Add decimal functionality

Now, tweak the code to add more functionality.

The current calculator app only accepts and returns whole numbers. For example, if you run the app and divide the number 42 by the number 119, your result is zero, which isn't exact.

Screenshot of a Console window that shows the Calculator app returning an inexact whole number as a result.

To fix the code to improve precision by handling decimals:

  1. From Program.cs in the Visual Studio editor, press Ctrl+H to open the Find and Replace control.

  2. Type int in the control, and type float in the Replace field.

  3. Select the icons for Match case and Match whole word in the control, or press Alt+C and Alt+W.

  4. Select the Replace all icon or press Alt+A to run the search and replace.

    Animation of the Find and Replace control showing how to change the int variable to float.

  5. Run your calculator app again, and divide the number 42 by the number 119.

    The app now returns a decimal number instead of zero.

    Screenshot of a Console window showing the Calculator app that now returns a decimal numeral as a result.

    Now the app can produce decimal results. Make a few more tweaks to the code so the app can calculate decimals too.

  6. Use the Find and Replace control to change each instance of the float variable to double, and to change each instance of the Convert.ToInt32 method to Convert.ToDouble.

  7. Run your calculator app, and divide the number 42.5 by the number 119.75.

    The app now accepts decimal values, and returns a longer decimal numeral as its result.

    Screenshot of a Console window showing the Calculator app that now accepts decimal numbers and returns a longer decimal result.

    In the Revise the code section, you reduce the number of decimal places in the results.

Debug the app

You improved your basic calculator app, but your app doesn't yet handle exceptions, such as user input errors. For example, if users try to divide by zero, or enter an unexpected character, the app might stop working, return an error, or return an unexpected non-numeric result.

Let's walk through a few common user input errors, locate them in the debugger if they appear there, and fix them in the code.

Tip

For more information about the debugger and how it works, see First look at the Visual Studio debugger.

Fix the "divide by zero" error

If you try to divide a number by zero, the console app might freeze, and then shows you what's wrong in the code editor.

Screenshot of the Visual Studio code editor showing a line highlighted in yellow and an Exception Unhandled error for 'Attempted to divide by zero'.

Note

Sometimes the app doesn't freeze, and the debugger doesn't show a divide-by-zero error. Instead, the app might return an unexpected nonnumeric result, such as an infinity symbol. The following code fix still applies.

Let's change the code to handle this error. In Program.cs, replace the code for case "d": with the following code:

            // Ask the user to enter a non-zero divisor until they do so.
                while (num2 == 0)
                {
                    Console.WriteLine("Enter a non-zero divisor: ");
                    num2 = Convert.ToDouble(Console.ReadLine());
                }
                Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
                break;
        }

After you replace the code, the section with the switch statement should look similar to the following screenshot:

Screenshot showing the revised switch section in the Visual Studio code editor.

Now, when you divide any number by zero, the app asks for another number, and keeps asking until you provide a nonzero number.

Screenshot of a Console window with a repeated prompt to provide a nonzero number.

Fix the "format" error

If you enter an alphabetic character when the app expects a numeric character, the app freezes. Visual Studio shows you what's wrong in the code editor.

Screenshot showing an unhandled format error in the Visual Studio code editor.

Screenshot showing an unhandled format error in the Visual Studio code editor.

To prevent this exception, you can refactor the code you've previously entered.

Revise the code

Rather than rely on the program class to handle all the code, you can divide your app into two classes: Calculator and Program.

The Calculator class handles the bulk of the calculation work, and the Program class handles the user interface and error-handling work.

Let's get started.

  1. In Program.cs, delete everything and add the following new Calculator class:

    class Calculator
    {
        public static double DoOperation(double num1, double num2, string op)
        {
            double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error.
    
            // Use a switch statement to do the math.
            switch (op)
            {
                case "a":
                    result = num1 + num2;
                    break;
                case "s":
                    result = num1 - num2;
                    break;
                case "m":
                    result = num1 * num2;
                    break;
                case "d":
                    // Ask the user to enter a non-zero divisor.
                    if (num2 != 0)
                    {
                        result = num1 / num2;
                    }
                    break;
                // Return text for an incorrect option entry.
                default:
                    break;
            }
            return result;
        }
    }
    
    
  2. Also add a new Program class, as follows:

    class Program
    {
        static void Main(string[] args)
        {
            bool endApp = false;
            // Display title as the C# console calculator app.
            Console.WriteLine("Console Calculator in C#\r");
            Console.WriteLine("------------------------\n");
    
            while (!endApp)
            {
                // Declare variables and set to empty.
                string numInput1 = "";
                string numInput2 = "";
                double result = 0;
    
                // Ask the user to type the first number.
                Console.Write("Type a number, and then press Enter: ");
                numInput1 = Console.ReadLine();
    
                double cleanNum1 = 0;
                while (!double.TryParse(numInput1, out cleanNum1))
                {
                    Console.Write("This is not valid input. Please enter a numeric value: ");
                    numInput1 = Console.ReadLine();
                }
    
                // Ask the user to type the second number.
                Console.Write("Type another number, and then press Enter: ");
                numInput2 = Console.ReadLine();
    
                double cleanNum2 = 0;
                while (!double.TryParse(numInput2, out cleanNum2))
                {
                    Console.Write("This is not valid input. Please enter a numeric value: ");
                    numInput2 = Console.ReadLine();
                }
    
                // Ask the user to choose an operator.
                Console.WriteLine("Choose an operator from the following list:");
                Console.WriteLine("\ta - Add");
                Console.WriteLine("\ts - Subtract");
                Console.WriteLine("\tm - Multiply");
                Console.WriteLine("\td - Divide");
                Console.Write("Your option? ");
    
                string op = Console.ReadLine();
    
                try
                {
                    result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                    if (double.IsNaN(result))
                    {
                        Console.WriteLine("This operation will result in a mathematical error.\n");
                    }
                    else Console.WriteLine("Your result: {0:0.##}\n", result);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
                }
    
                Console.WriteLine("------------------------\n");
    
                // Wait for the user to respond before closing.
                Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
                if (Console.ReadLine() == "n") endApp = true;
    
                Console.WriteLine("\n"); // Friendly linespacing.
            }
            return;
        }
    }
    
  3. Select the Calculator button or press F5 to run your app.

  4. Follow the prompts and divide the number 42 by the number 119. Your results should look similar to the following screenshot:

    Screenshot showing a Console window with the refactored Calculator app.

    You can now run more calculations until you choose to close the console app. There are also fewer decimal places in the results. And if you enter an incorrect character, you get an appropriate error response.

Revise the code

Rather than rely on the program class to handle all the code, you can divide your app into two classes: Calculator and Program.

The Calculator class handles the bulk of the calculation work, and the Program class handles the user interface and error-handling work.

Let's get started.

  1. In Program.cs, delete everything and add the following new Calculator class:

    class Calculator
    {
        public static double DoOperation(double num1, double num2, string op)
        {
            double result = double.NaN; // Default value is "not-a-number" if an operation, such as division, could result in an error.
    
            // Use a switch statement to do the math.
            switch (op)
            {
                case "a":
                    result = num1 + num2;
                    break;
                case "s":
                    result = num1 - num2;
                    break;
                case "m":
                    result = num1 * num2;
                    break;
                case "d":
                    // Ask the user to enter a non-zero divisor.
                    if (num2 != 0)
                    {
                        result = num1 / num2;
                    }
                    break;
                // Return text for an incorrect option entry.
                default:
                    break;
            }
            return result;
        }
    }
    
    
  2. Also add a new Program class, as follows:

    class Program
    {
        static void Main(string[] args)
        {
            bool endApp = false;
            // Display title as the C# console calculator app.
            Console.WriteLine("Console Calculator in C#\r");
            Console.WriteLine("------------------------\n");
    
            while (!endApp)
            {
                // Declare variables and set to empty.
                // Use Nullable types (with ?) to match type of System.Console.ReadLine
                string? numInput1 = "";
                string? numInput2 = "";
                double result = 0;
    
                // Ask the user to type the first number.
                Console.Write("Type a number, and then press Enter: ");
                numInput1 = Console.ReadLine();
    
                double cleanNum1 = 0;
                while (!double.TryParse(numInput1, out cleanNum1))
                {
                    Console.Write("This is not valid input. Please enter a numeric value: ");
                    numInput1 = Console.ReadLine();
                }
    
                // Ask the user to type the second number.
                Console.Write("Type another number, and then press Enter: ");
                numInput2 = Console.ReadLine();
    
                double cleanNum2 = 0;
                while (!double.TryParse(numInput2, out cleanNum2))
                {
                    Console.Write("This is not valid input. Please enter a numeric value: ");
                    numInput2 = Console.ReadLine();
                }
    
                // Ask the user to choose an operator.
                Console.WriteLine("Choose an operator from the following list:");
                Console.WriteLine("\ta - Add");
                Console.WriteLine("\ts - Subtract");
                Console.WriteLine("\tm - Multiply");
                Console.WriteLine("\td - Divide");
                Console.Write("Your option? ");
    
                string? op = Console.ReadLine();
    
                // Validate input is not null, and matches the pattern
                if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]"))
                {
                   Console.WriteLine("Error: Unrecognized input.");
                }
                else
                { 
                   try
                   {
                      result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                      if (double.IsNaN(result))
                      {
                         Console.WriteLine("This operation will result in a mathematical error.\n");
                      }
                      else Console.WriteLine("Your result: {0:0.##}\n", result);
                    }
                    catch (Exception e)
                    {
                       Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
                    }
                }
                Console.WriteLine("------------------------\n");
    
                // Wait for the user to respond before closing.
                Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
                if (Console.ReadLine() == "n") endApp = true;
    
                Console.WriteLine("\n"); // Friendly linespacing.
            }
            return;
        }
    }
    

    Note

    It's best to use nullable types (with the ? symbol) for the input strings, since System.Console.ReadLine returns a nullable reference type.

  3. Select the Calculator button or press F5 to run your app.

  4. Follow the prompts and divide the number 42 by the number 119. Your results should look similar to the following screenshot:

    Screenshot showing a Console window with the refactored Calculator app.

    You can now run more calculations until you choose to close the console app. There are also fewer decimal places in the results. And if you enter an incorrect character, you get an appropriate error response.

Close the app

  1. If you haven't already done so, close the Calculator app.

  2. Close the Output pane in Visual Studio.

    Screenshot that shows closing the Output pane in Visual Studio.

  3. In Visual Studio, press Ctrl+S to save your app.

Add Git source control

Now that you have an application, you might want to add it to a Git repository. Visual Studio makes that process easy with Git tools you can use directly from the IDE.

Tip

Git is the most widely used modern version control system. Whether you're a professional developer or you're learning how to code, Git can be very useful. If you're new to Git, the https://git-scm.com/ website is a good place to start. You can find cheat sheets, a popular online book, and Git Basics videos.

To associate your code with Git, start by creating a new Git repository where your code is located:

  1. In the status bar at the bottom-right of Visual Studio, select Add to Source Control, and then select Git.

    Screenshot that shows how to access the Git source control action from Add to Source Control in Visual Studio.

  2. In the Create a Git repository dialog box, sign in to GitHub:

    Screenshot of the Create a Git Repository dialog window where you can sign in to GitHub.

    The repository name autopopulates based on your folder location. Your new repository is private by default, which means you're the only one who can access it.

    Tip

    Whether your repository is public or private, it's best to have a remote backup of your code stored securely on GitHub. Even if you aren't working with a team, a remote repository makes your code available to you from any computer.

  3. Select Create and Push. After you create your repository, you see status details in the status bar:

    Screenshot of the repo status bar below the Solution Explorer pane in Visual Studio.

Use Git actions in Visual Studio

Here's a brief summary of Git actions available in the Visual Studio status bar:

  • The Up/Down arrows show how many outgoing/incoming commits are in your current branch. You can use this icon to pull any incoming commits or push any outgoing commits.

  • To view a specific commit, select the Up/Down arrow, and then select View Outgoing/Incoming.

  • The Pencil shows the number of uncommitted changes to your code. You can select this icon to view those changes in the Git Changes window.

The Git menu provides tools for repository actions on your files. You can use git fetch, pull, push, and sync for version control in Visual Studio.

For more information about how to use Git with your app, see About Git in Visual Studio.

Review: Code complete

In this tutorial, you made many changes to the Calculator app. The app now handles computing resources more efficiently, and handles most user input errors.

Here's the complete code, all in one place:


class Calculator
{
    public static double DoOperation(double num1, double num2, string op)
    {
        double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.

        // Use a switch statement to do the math.
        switch (op)
        {
            case "a":
                result = num1 + num2;
                break;
            case "s":
                result = num1 - num2;
                break;
            case "m":
                result = num1 * num2;
                break;
            case "d":
                // Ask the user to enter a non-zero divisor.
                if (num2 != 0)
                {
                    result = num1 / num2;
                }
                break;
            // Return text for an incorrect option entry.
            default:
                break;
        }
        return result;
    }
}

class Program
{
    static void Main(string[] args)
    {
        bool endApp = false;
        // Display title as the C# console calculator app.
        Console.WriteLine("Console Calculator in C#\r");
        Console.WriteLine("------------------------\n");

        while (!endApp)
        {
            // Declare variables and set to empty.
            string numInput1 = "";
            string numInput2 = "";
            double result = 0;

            // Ask the user to type the first number.
            Console.Write("Type a number, and then press Enter: ");
            numInput1 = Console.ReadLine();

            double cleanNum1 = 0;
            while (!double.TryParse(numInput1, out cleanNum1))
            {
                Console.Write("This is not valid input. Please enter a numeric value: ");
                numInput1 = Console.ReadLine();
            }

            // Ask the user to type the second number.
            Console.Write("Type another number, and then press Enter: ");
            numInput2 = Console.ReadLine();

            double cleanNum2 = 0;
            while (!double.TryParse(numInput2, out cleanNum2))
            {
                Console.Write("This is not valid input. Please enter a numeric value: ");
                numInput2 = Console.ReadLine();
            }

            // Ask the user to choose an operator.
            Console.WriteLine("Choose an operator from the following list:");
            Console.WriteLine("\ta - Add");
            Console.WriteLine("\ts - Subtract");
            Console.WriteLine("\tm - Multiply");
            Console.WriteLine("\td - Divide");
            Console.Write("Your option? ");

            string op = Console.ReadLine();

            try
            {
                result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                if (double.IsNaN(result))
                {
                    Console.WriteLine("This operation will result in a mathematical error.\n");
                }
                else Console.WriteLine("Your result: {0:0.##}\n", result);
            }
            catch (Exception e)
            {
                Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
            }

            Console.WriteLine("------------------------\n");

            // Wait for the user to respond before closing.
            Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
            if (Console.ReadLine() == "n") endApp = true;

            Console.WriteLine("\n"); // Friendly linespacing.
        }
        return;
    }
}


class Calculator
{
    public static double DoOperation(double num1, double num2, string op)
    {
        double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.

        // Use a switch statement to do the math.
        switch (op)
        {
            case "a":
                result = num1 + num2;
                break;
            case "s":
                result = num1 - num2;
                break;
            case "m":
                result = num1 * num2;
                break;
            case "d":
                // Ask the user to enter a non-zero divisor.
                if (num2 != 0)
                {
                    result = num1 / num2;
                }
                break;
            // Return text for an incorrect option entry.
            default:
                break;
        }
        return result;
    }
}

class Program
{
    static void Main(string[] args)
    {
        bool endApp = false;
        // Display title as the C# console calculator app.
        Console.WriteLine("Console Calculator in C#\r");
        Console.WriteLine("------------------------\n");

        while (!endApp)
        {
            // Declare variables and set to empty.
            // Use Nullable types (with ?) to match type of System.Console.ReadLine
            string? numInput1 = "";
            string? numInput2 = "";
            double result = 0;

            // Ask the user to type the first number.
            Console.Write("Type a number, and then press Enter: ");
            numInput1 = Console.ReadLine();

            double cleanNum1 = 0;
            while (!double.TryParse(numInput1, out cleanNum1))
            {
                Console.Write("This is not valid input. Please enter a numeric value: ");
                numInput1 = Console.ReadLine();
            }

            // Ask the user to type the second number.
            Console.Write("Type another number, and then press Enter: ");
            numInput2 = Console.ReadLine();

            double cleanNum2 = 0;
            while (!double.TryParse(numInput2, out cleanNum2))
            {
                Console.Write("This is not valid input. Please enter a numeric value: ");
                numInput2 = Console.ReadLine();
            }

            // Ask the user to choose an operator.
            Console.WriteLine("Choose an operator from the following list:");
            Console.WriteLine("\ta - Add");
            Console.WriteLine("\ts - Subtract");
            Console.WriteLine("\tm - Multiply");
            Console.WriteLine("\td - Divide");
            Console.Write("Your option? ");

            string? op = Console.ReadLine();

            // Validate input is not null, and matches the pattern
            if (op == null || ! Regex.IsMatch(op, "[a|s|m|d]"))
            {
                Console.WriteLine("Error: Unrecognized input.");
            }
            else
            { 
                try
                {
                    result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                    if (double.IsNaN(result))
                    {
                        Console.WriteLine("This operation will result in a mathematical error.\n");
                    }
                    else Console.WriteLine("Your result: {0:0.##}\n", result);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
                }
            }
            Console.WriteLine("------------------------\n");

            // Wait for the user to respond before closing.
            Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
            if (Console.ReadLine() == "n") endApp = true;

            Console.WriteLine("\n"); // Friendly linespacing.
        }
        return;
    }
}

Next steps

Continue with the second part of this tutorial: