C# Fundamentals

From the previous sections, you have understood that what is C#, and what we can do with C#.

In this section, we will create a basic C# program and by using it, we will understand the fundamentals of C# programming.

Example

Try It
using System;
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            string messgae = "Hello from TutorialsLeader";
            Console.WriteLine(messgae);
            Console.WriteLine("Hello from TutorialsLeader.");
            Console.ReadLine();
            return;
        }
    }
}

Quick Explanation

Explanation of above points

In the above example, the first few lines are related with the namespaces. On the very first line, there is an using System statement. This statement tells the compiler to find any classes that are referenced in the code but aren't defined in the current namespace that is TutorialsLeader.

We have used using System in the above code because we are using WriteLine() function of Console class, which resides under System namespace.

If we do not use the using statement, Then we would have to specify the fully qualified name to use the function of Console class. like :

System.Console.WriteLine("Hello from Tutorialsleader.");

In the above example, we have created the namespace using namespace TutorialsLeader

On the next line, we have created a class. The above class resides under TutorialsLeader namespace, so the fully qualified name of this class will be TutorialsLeader.MyFirstClass

In c# we can declare a class by using class keyword and the class name followed by two curly braces. Following is the syntax to declare a class.

class ClassName
{
    //Class Body
}

All the code in c# must be written inside a class, the properties, methods etc which we want to associate with this class must be inside the two curly braces.

On the next line, we have created a method called Main(). For any console or windows application, it requires having an entry point.

When the program gets started the Main() method called at very first.

Following is the syntax to declare a Main() method in C#.

[modifiers] return_type MethodName([parameters])
{
    // Method body.
}

At the end of the above program, we have called the method WriteLine() of Console class to print a message on the Console. When the above program gets executed it prints the below messages.

Output

Hello from TutorialsLeader

Hello from TutorialsLeader

This was an overview and explanation of a simple C# program. Let's learn about the Variables in C# in the next Section.