Wednesday, December 3, 2008

Static class:

Static Class:
  • No need to create instance for the 'static class'.
  • Inside static class, we can use only static members.
  • If use the other than static members inside the static class, the compiler will throw error.
  • We can directly access the members using class name.member name , for Ex:Program.display();Here Program is the class name and display is the method name.
  • We can't derive static class.
Example:

namespace ConsoleApplication6
{
static class Program
{
static int a = 10;
static void display()
{
Console.WriteLine(a);
Console.ReadLine();
}
static void menu()
{
Console.WriteLine("TOTAL="+ (a+a+a) );
Console.ReadLine();
}

static void Main(string[] args)
{

Program.display();
Program.menu();

}
}
}

Output:

10
Total:30

If use other than static members inside the static class, the compiler will throw error.

Example:
namespace ConsoleApplication6
{
static class Program
{

public void message()
{
Console.WriteLine(a);
Console.ReadLine();
}
static void Main(string[] args)
{

}
}
}

Output:

Error 1 'message'
: cannot declare instance members in a static class

No comments: