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.