官术网_书友最值得收藏!

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 compile a source file into a shared library:

csc my.cs /target:library

To encrypt the database connection strings section in a Web.config file, use the following command:

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 lines. 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 has a handy new 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 code in the Main method:

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

Press Ctrl + F5 and view the output in the console:

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

The variable can be formatted using special format codes. 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 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 name and press ENTER: ");
string name = Console.ReadLine();
Console.Write("Type your age and press ENTER: ");
string age = Console.ReadLine();
Console.WriteLine($"Hello {name}, you look good for {age}.");

Press Ctrl + F5 and view the output in the console. Enter a name and an age:

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 added a line 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. We call this importing the namespace.

using System;

Simplifying the usage of the console in C# 6

In C# 6, 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).

Press Ctrl + H to do a Quick Replace (ensure that the Replace… box is empty).

Press Alt + A to replace all and then click on OK.

Close the replace box by clicking on the cross in its top-right corner.

We can use a Visual Studio feature to clean up the extra using statements that we don't need.

Click on the using statements, click on the light bulb icon that appears (or press Ctrl + .), and then select Remove Unnecessary Usings:

Our complete application now looks like the following code:

using static System.Console;

namespace Ch02_Variables
{
    class Program
    {
        static void Main(string[] args)
        {
            var population = 66000000;
            var weight = 1.88; // in kilograms
            var price = 4.99M; // in pounds sterling
            var fruit = "Apples"; // strings use double-quotes
            var letter = 'Z'; // chars use single-quotes
            var happy = true;

            int ICannotBeNull = 4;
            ICannotBeNull = default(int); // 0
            int? ICouldBeNull = null;
            var result1 = ICouldBeNull.GetValueOrDefault(); // 0
            ICouldBeNull = 4;
            var result2 = ICouldBeNull.GetValueOrDefault(); // 4 

            // declaring the size of the array
            string[] names = new string[4];
            // storing items at index positions
            names[0] = "George";
            names[1] = "Jerry";
            names[2] = "Elaine";
            names[3] = "Cosmo";
            for (int i = 0; i < names.Length; i++)
            {
                WriteLine(names[i]); // read the item at this index
            }

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

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

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.

Remember how we could pass the name of the file we wanted to compile to the compiler when we used the C# compiler at the Command Prompt? We can do the same thing with our own applications. For example, we can enter the following 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.

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.");
        }
    }
}
Tip

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

Press Ctrl + F5 and view the output in the console:

There are 0 arguments.

To pass in some arguments, view the Solution Explorer window, and inside the Ch02_Arguments project, double-click on Properties:

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

firstarg second-arg third:arg "fourth arg"

Note that 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.

Press Ctrl + F5 and view the output in the console:

There are 4 arguments.

To enumerate or iterate (that is, loop through) the values of those four arguments, add these three 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 arguments in the Properties window to look like this:

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

using System;

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);
}

We needed 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.

Press Ctrl + F5. The console window is now a different size and uses different colors for the foreground and background text.

主站蜘蛛池模板: 仙游县| 蚌埠市| 疏附县| 班戈县| 夏津县| 阿拉善右旗| 富裕县| 岐山县| 塔河县| 米林县| 西乌| 黄浦区| 成武县| 江北区| 天门市| 吉隆县| 台中县| 安泽县| 齐河县| 建阳市| 调兵山市| 敖汉旗| 治多县| 确山县| 大田县| 阿瓦提县| 潼关县| 连城县| 桃园县| 民乐县| 兴义市| 孝感市| 天长市| 岗巴县| 和林格尔县| 本溪市| 宜州市| 宁蒗| 吴江市| 乡城县| 巍山|