Structure of a C# Program
Learn about how C# programs are structured.
We'll cover the following...
Statements and code blocks
C# code files are text files with .cs extension. They contain instructions that’re compiled to
Statements are the basic building blocks of C# source code. A statement can be some action, such as an arithmetic operation, a method invocation, or a variable declaration and assignment.
Console.WriteLine("This is a statement.");
Like in C and C++, every statement must be followed by a semicolon (;). Leaving them out results in compilation errors, and our program won’t compile to IL.
We can combine a set of instructions into blocks of code. To create a code block, we enclose our statements in curly braces.
{
Console.WriteLine("I am inside a block!");
Console.WriteLine("Me too.");
}
Blocks can contain other blocks. Essentially, both a class and a method can be seen as code blocks. A class contains a method, and a method contains instructions within its curly braces.
Curly braces and blocks will become much more useful when we start using constructs like loops and methods.
The Main() method
Any .NET program must have a Main() method, unless it’s a class library that’s consumed by other applications. All executable programs have a Main() method that serves as the application’s entry point.
Let’s experiment a bit. We want to see what happens if we remove the Main() method in our code or rename it and try to execute the program.
Rename the Main() method in the following code to any valid name and try to run it.
Notice the following:
error CS5001: Program `main.exe' does not contain a static `Main' method suitable for an entry point
After looking for the Main() method and failing to find it, the CLR generated this error.
Case sensitivity
C# is case-sensitive. This means that depending on the character case, the same names can represent different classes, methods, and variables.
For instance, in the following code, we have a class named Program. We can create another class just below and name it program. No error is generated because these classes aren’t the same, because of that case sensitivity.
Comments
Comments are an important part of source code. They’re ignored during compilation and are absent in the generated IL. They’re used constantly, however, because they make code more readable, improving the potential for collaboration.
The following code snippet shows different types of comments in C#.
As we can see, we can write multi-line comments by putting the text between /* and */.
/*
I am a multi-line comment.
The second line of the comment.
*/
The // denotes the beginning of a single-line comment. Any text after // is regarded as a comment and is ignored by the compiler.
// I am single-line comment.