Building console applications

Console applications are text-based and are run at the command prompt. They typically perform simple tasks that need to be scripted, such as compiling a file or encrypting a section of a configuration file. They can have arguments passed to them to control their behavior for example, to encrypt the database connection strings section in a Web.config file, use the following command line:

aspnet_regiis -pdf "connectionStrings" "c:mywebsite" 

Displaying output to the user

The two most common tasks that a console application performs are writing and reading data. We have already been using the WriteLine method to output. If we didn't want a carriage return at the end of lines, we could have used the Write method.

C# 6 and later has a handy feature named string interpolation. This allows us to easily output one or more variables in a nicely formatted manner. A string prefixed with $ can use curly braces around the name of a variable to output the current value of that variable at that position in the string.

In the Ch02_Variables project, enter the following statements at the bottom of the Main method:

    Console.WriteLine($"The UK population is {population}."); 
    Console.Write($"The UK population is {population:N0}. "); 
    Console.WriteLine($"{weight}kg of {fruit} costs {price:C}."); 

Run the console application and view the output:

The population of the UK is 66000000.
The population of the UK is 66,000,000. 1.88kg of Apples costs £4.99.

A variable can be formatted using special pieces of code. N0 means a number with commas for thousands and no decimal places. C means currency. The currency format will be determined by the current thread. If you run this code on a PC in the UK, you get pounds sterling. If you run this code on a PC in Germany, you would get Euros.

Getting input from the user

We can get input from the user using the ReadLine method. This method waits for the user to type some text. As soon as the user presses Enter, whatever the user has typed is returned as a string.

Let's ask the user for their name and age. Later, we will convert the age into a number, but we will leave it as a string for now:

    Console.Write("Type your first name and press ENTER: "); 
    string firstName = Console.ReadLine(); 
    Console.Write("Type your age and press ENTER: "); 
    string age = Console.ReadLine(); 
    Console.WriteLine($"Hello {firstName}, you look good for {age}."); 

Run the console application and view the output.

Enter a name and an age, as shown in the following output:

Type your name and press ENTER: Gary
Type your age and press ENTER: 34
Hello Gary, you look good for 34.

Importing a namespace

You might have noticed that unlike our very first application, we have not been typing System before Console.

System is a namespace. Namespaces are like an address for a type. To refer to someone exactly, you might use Oxford.HighStreet.BobSmith, which tells us to look for a person named Bob Smith on the High Street in the city of Oxford.

The line System.Console.WriteLine tells the compiler to look for a method named WriteLine in a type named Console in a namespace named System.

To simplify our code, Visual Studio 2017, or the dotnet new console command when using Visual Studio Code, added a statement at the top of the code file to tell the compiler to always look in the System namespace for types that haven't been prefixed with their namespace, as shown in the following code:

    using System; 

We call this importing the namespace.

Simplifying the usage of the console

In C# 6 and later, the using statement can be used to further simplify our code.

Add the following line to the top of the file:

    using static System.Console; 

Now, we don't need to enter the Console type throughout our code. We can use Find and Replace to remove it.

Select the first Console. line in your code (ensure that you select the dot after the word Console).

In Visual Studio 2017, press Ctrl + H to do a Quick Replace (ensure that the Replace... box is empty), as shown in the following screenshot:

Simplifying the usage of the console

In Visual Studio Code, choose Edit, and then Replace, as shown in the following screenshot:

Simplifying the usage of the console

In both Visual Studio 2017 and Visual Studio Code, click the Replace All button or press Alt + A or Alt + Cmd + Enter to replace all, click on OK, and then close the replace box by clicking on the cross in its top-right corner.

Reading arguments and working with arrays

You have probably been wondering what the string[] args argument is in the Main method. It is an array used to pass arguments into a console application.

Add a new console application project named Ch02_Arguments.

Imagine that we want to be able to enter the following command at the command prompt:

Ch02_Arguments apples bananas cherries

We would be able to read the fruit names by reading them from the args array that is always passed into the Main method of a console application.

Remember that arrays use the square bracket syntax to indicate multiple values. Arrays have a property named Length that tells us how many items are currently in the array. If there is at least one item, then we can access it by knowing its index. Indexes start counting from zero, so the first item in an array is item 0.

Add a statement to statically import the System.Console type. Write a statement to output the number of arguments passed to the application. Remove the unnecessary using statements. Your code should now look like this:

    using static System.Console; 
 
    namespace Ch02_Arguments 
    { 
      class Program 
      { 
        static void Main(string[] args) 
        { 
          WriteLine($"There are {args.Length} arguments."); 
        } 
      } 
    } 

Note

Remember to statically import the System.Console type in future projects to simplify your code, as these instructions will not be repeated.

Run the console application and view the output:

There are 0 arguments.

Passing arguments with Visual Studio 2017

In Solution Explorer, right-click the Ch02_Arguments project, and choose Properties.

In the Properties window, select the Debug tab, and in the Application arguments box, enter a space-separated list of four arguments, as shown in the following code and screenshot:

    firstarg second-arg third:arg "fourth arg" 

Passing arguments with Visual Studio 2017

Note

You can use almost any character in an argument, including hyphens and colons. If you need to use a space inside an argument, you must wrap it in double quotes.

Passing arguments with Visual Studio Code

Type arguments after the dotnet run command, as shown in the following example:

dotnet run firstarg second-arg third:arg "fourth arg"

Viewing the output

Run the console application with passed arguments, and view the output:

There are 4 arguments.

Enumerating arguments

To enumerate or iterate (that is, loop through) the values of those four arguments, add the following lines of highlighted code after outputting the length of the array:

    WriteLine($"There are {args.Length} arguments."); 
    foreach (string arg in args)

    {

      WriteLine(arg);
} 

We will now use these arguments to allow the user to pick a color for the background, foreground, width, and height of the console window.

Change the argument values to the following:

red yellow 50 10

Import the System namespace by adding the following line to the top of the code file if it is not already there:

    using System; 

Note

We need to import the System namespace so that the compiler knows about the ConsoleColor and Enum types. If you cannot see either of these types in the IntelliSense list, it is because you are missing the using System; statement.

Add the highlighted code on top of the existing code like this:

    ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor),
    args[0], true);

    BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor),
    args[1], true);

    WindowWidth = int.Parse(args[2]);

    WindowHeight = int.Parse(args[3]); 
 
    WriteLine($"There are {args.Length} arguments."); 
    foreach (var arg in args) 
    { 
      WriteLine(arg); 
    } 

Running on Windows

In Visual Studio 2017, press Ctrl + F5. The console window is now a different size and uses different colors for the foreground and background text, as shown in the following screenshot:

Running on Windows

Running on macOS

In Visual Studio Code, enter the following command at the terminal:

dotnet run red yellow 50 10

You will see an error dialog, as shown in the following screenshot:

Running on macOS

Click OK.

In the Terminal, you will see the details of the error, as shown in the following screenshot:

Running on macOS

Note

Although the compiler did not give an error or warning, at runtime some API calls may fail on some platforms. Although a console application running on Windows can change its size, on macOS it cannot.

Handling platforms that do not support an API

We can solve this problem by using an exception handler. Modify the code to wrap the lines that change the height and width in a try statement like this:

    try 
    { 
      WindowWidth = int.Parse(args[2]); 
      WindowHeight = int.Parse(args[3]); 
    } 
    catch(PlatformNotSupportedException) 
    { 
      WriteLine("The current platform does not support changing the
      size of a console window."); 
    } 

If you rerun the console application, you will see the exception is caught and a friendly message is shown to the user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.235.62