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

Writing your first C# program in a console application

As you are now aware of the fundamentals and basics of the C# language, literals, loops, conditions, and so on, I think it is time to see a C# code example. So, let's start this section by writing a simple console application, compiling it, and running it using the C# compiler.

Open any notepad application that you have in your computer and type in the following code:

using System;

public Program
{
static void Main(string[] args)
{
int num, sum = 0, r;
Console.WriteLine("Enter a Number : ");
num = int.Parse(Console.ReadLine());
while (num != 0)
{
r = num % 10;
num = num / 10;
sum = sum + r;
}
Console.WriteLine("Sum of Digits of the Number : " + sum);
Console.ReadLine();
}
}

The preceding code is a classic example of calculating the sum of all of the digits of a number. It takes a number as input using the Console.ReadLine() function, parses it, and stores it into a variable, num, loops through while the number is 0, and takes modulus by 10 to get the reminder of the division, which is then summed up to produce the result.

You can see there is a using statement at the top of the code block, which ensures that Console.ReadLine() and Console.WriteLine() can be called. System is a namespace from the code, which enables the program to call the classes defined inside it without specifying the full namespace path of the class.

Let's save the class as program.cs.  Now, open the console and move it to the location where you have saved the code.

To compile the code, we can use the following command:

csc Program.cs

The compilation will produce something like this:

The compilation will produce program.exe. If you run this, it will take the number as input and produce the result:

You can see that the code is being executed in the console window.

If we dissect how the code is being executed further, we can see that the .NET framework provides the csc compiler, an executable that is capable of compiling my C# code into a managed executable. The compiler produces an executable with MSIL as its content, and then, when the executable is being executed, the .NET framework invokes an executable and uses JIT to compile it further so that it can interact with the input/output devices.

The csc compiler provides various command-line hooks, which can be used further to add dynamic link library (dll) references to the program, target the output as dll, and much more. You can find the full functional document at the following link: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/listed-alphabetically.

主站蜘蛛池模板: 万荣县| 南康市| 禹州市| 会泽县| 桓仁| 揭阳市| 宣城市| 清水河县| 高邮市| 七台河市| 长沙县| 大荔县| 九寨沟县| 象州县| 什邡市| 柏乡县| 安塞县| 博客| 汕头市| 襄樊市| 杭锦旗| 鹤岗市| 星子县| 鹤山市| 温宿县| 苏州市| 绥化市| 隆回县| 那坡县| 若尔盖县| 晴隆县| 眉山市| 富宁县| 喜德县| 南溪县| 合肥市| 正镶白旗| 唐海县| 黔西县| 合阳县| 如东县|