Introduction of Static Keyword in C#.net

Introduction of Static Keyword in C#.net

Static Class :

A static class is you can say same as the non-static class, but there is one difference them is a static class can’t be instantiated. In other words, you cannot use the “new” keyword to create a instance variable of the class type. As there is no instance variable, you can access the members of a static class by using the name of the class itself. Static classes and it’s class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when data or behavior is not present in the class that depends on object identity. Static classes are loaded automatically by the .NET Framework CLR when that program or namespace containing the class is loaded.

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(); } }

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply