In this article, we will be discussing about C# syntaxes and comments.
Syntax
Let’s create a Hello World! Console app and have a close look at it.
using System;
namespace FirstConsoleApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
Let’s traverse line by line, understanding them.
- using System; → It says that use the pre-defined, already available System namespace. The Console class resides in the System namespace
- namespace FirstConsoleApplication → It says that we have defined our own namespace, which is known as FirstConsoleApplication.
Visual Studio takes in the project name, which we provide at the time of project creation, and tends to wrap our code inside a namespace with that very project name.
- class Program → It says that a class named as Program exists.
Class is nothing but an encapsulation which contains members and states.
We would deep dive into classes in a separate article.
- static void Main → It says that a static method named as Main is created, which returns nothing, hence the return type is void.
- Console.WriteLine(“Hello World!”); → It says that a text “Hello World!” is written onto the console output.
Every single line of code in C# should end with a semicolon.
The syntax of C# programming language is quite simple and easy to understand. A regular practice is needed, though.
Comments
Comments play a vital role in any C# code.
Developers should be cautious writing comments in their code, not to over do them, but to maintain a level which would make the code much readable.
Let’s see how to write comments in C# code.
- Single line comments
These are written using //.
Any text written after // is perceived as a comment and is ignored by the C# compiler.
//The below line prints Hello World to the console.
Console.WriteLine("Hello World!");
Console.WriteLine("Hello from the USA"); // This is also a comment.
- Multi line comments
Multi line comments are wrapped between /* and */
/* The below method adds 10 and 20.
Then it outputs the sum to the console.
*/
var sum = 10 + 20;
Console.WriteLine(sum);
Generally, multi-line comments are used to write a bunch of sentences as comments, while singe line comments are used for shorter texts.
