Static Class :
The main features of a static class are:
- static classes can only contain static members.
- static classes can not be instantiated.
- static classes are sealed and therefore cannot be inherited.
- static classes can not contain Instance Constructors (C# Programming Guide).
public static class Settings { static int i; public static string GetName() { return "MyName"; } } class Program { static void Main(string[] args) { string str=Settings.GetName(); Console.Write(str); Console.Read(); } }
Static Fields:
Static fields can be declared by using the keyword static. class MySettings { public static int height; public static int width = 20; }
When we declare a static field inside a class, it can be initialized as shown above in the example with a value. All un-initialized static fields get automatically initialized to their default values when the containing class is loaded for the first time.
For example
class MySettings
{
public static int height = 20;
public static int width;
public static int length = 25;
public MySettings(int i)
{
height = i; width = i; length = i;
}
}
class AllSettings
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MySettings.height, MySettings.width, MySettings.length); MySettings mc = new MySettings(25);
Console.WriteLine("{0},{1},{2}", MySettings.height, MySettings.width, MySettings.length);
}
}
Static Method:
Static methods can be declared using Static keyword befor method name. The static methods can by accessed directly from the class. Static methods are normally faster to invoke on the call stack than instance methods
class MySettings
{
private static int height = 100; private static int width = 150;
public static void MyMethod() {
Console.WriteLine("{0},{1}", height, width);
} }
class AllSettings { public static void Main() { MyClass.MyMethod(); } }