C# Examples

C# Example Code


C# Program Structure

Before start CSharp in details, here it is important to understand the basic C# program structure. It is important to remember below points about CSharp:

  • CSharp is case sensitive.
  • All statements and expression must end with a semicolon (;).
  • The program execution starts at the Main method.
  • Program file name could be different from the class name.

The basic structure of CSharp program encompasses the below elements.

  • Namespace
  • Class
  • Class Properties
  • Class Methods
  • Main Method
  • Statements and Expressions

Simple "Hello World" example of C# and program structure.

Syntax

using System;
namespace SayHelloApplication
{
	class HelloWorldDemo
	{
		static void main()
		{
			Console.WriteLine("Hello World!");
		}
	}
}

Here it is important to understand each element of the program.

In the very first line program includes System namespace; to include namespace the using keyword is used. Namespace includes depends on program requirement.

In the second line, program require unique namespace name. A namespace consist of collection of classes. Here program has "SayHelloApplication" namespace that contains "HelloWorld" class.

In the third line, program declares class "HelloWorldDemo". A class can contains class fields and methods for example "Main" in above example.

In the fourth line, program defines "Main" method, which is the entry point in C# programs. The "Main" method has print statement which will execute when program run and print "Hello World".

CSharp program can be created either using Visual Studio .NET or using any text editor.