Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



Program Structure

C# programs can consist of one or more files. Each file can contain one or more namespaces. A namespace can contain types such as classes, structs, interfaces, enumerations, and delegates, in addition to other namespaces. The following is the skeleton of a C# program that contains all of these elements.


using System;
namespace MyNamespace1
{
class MyClass1
{
}
struct MyStruct
{
}
interface IMyInterface
{
}
delegate int MyDelegate();
enum MyEnum
{
}
namespace MyNamespace2
{
}
class MyClass2
{
public static void Main(string[] args)
{
}
}
}
Hello World Program

The following examples show different ways of writing the C# Hello World program.


// Hello1.cs
public class Hello1
{
public static void Main()
{
System.Console.WriteLine("Hello, World!");
}
}

Output

Hello, World!

To avoid fully qualifying classes throughout a program, you can use the using directive as shown below:


// Hello2.cs
using System;

public class Hello2
{
public static void Main()
{
Console.WriteLine("Hello, World!");
}
}

Output

Hello, World!

If you need access to the command line parameters passed in to your application, simply change the signature of the Main method to include them as shown below. This example counts and displays the command line arguments.


// Hello3.cs
// arguments: A B C D
using System;

public class Hello3
{ public static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Console.WriteLine("You entered the following {0} " +
"command line arguments:",
args.Length );
for (int i=0; i < args.Length; i++)
{
Console.WriteLine("{0}", args[i]);
}
}
}

Output

Hello, World!
You entered the following 4 command line arguments:
A
B
C
D

To return a return code, change the signature of the Main method as shown below.


// Hello4.cs
using System;
public class Hello4
{
public static int Main(string[] args)
{
Console.WriteLine("Hello, World!");
return 0;
}
}

Output

Hello, World!


Related Videos