- A static class can be created using a keyword called ―static‖ used at the class definition.
- A static class can contain only static members (static data members and static methods).
- You can‘t create an object for the static class.
Advantages :
- If you declare any non-static member, it generates a compile time error; so that it is guaranteed that the class contains only static members; no chance of declaring non-static member accidentally.
- When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name.
Syntax :
static class classname
{
//static data members
//static methods
}
Program for Static Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticClassesDemo
{
static class Sample
{
public static string SampleStaticMember = "This is my static data member";
public static void SampleStaticMethod()
{
Console.WriteLine("This is my static method.");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Sample.SampleStaticMember);
Sample.SampleStaticMethod();
Console.Read();
}
}
}
0 Comments