Header Ads

C# Static Method,Static Class,Static Variable and Static constructor


C#-static-keyword
Static Method:
1.When we have all static methods in a class, then we can declare that class as static class
2.Static methods are called with classname.method name directly with out creating object.
class static sample
{
public static void display()
{
MessageBox.Show("Am from static method");
}
button click
{
sample obj=new sample(); // error . As we cannot create object for static class.
obj.display(); // this is error. cannot be accessed with object.
sample.display(); //works fine as called with classname.methodname
}

Static class:
1. Static class cannot be instantiated, i.e., we cannot create object for static class.
2. If we have all static methods in our class then we can declare the class as static class.
class static sample1
{
public static string s="hello";
public static string st="am static variable";
public static void display()
{
MessageBox.Show("Am from static method");
MessageBox.Show("Am static class");
}
static sample1() // static constructor
{
MessageBox.Show("Am from static constructor");
}
button click
{
sample1.s;
sample1.st;
sample1.display();
}

Static variable:
1. Static keyword can be used with variables, methods, constructor and class.
2. Static variable will be created only once and it can be shared by all objects.
3. If we declare static variable as public, then we can access that variable with classname.static_vairable.
4.Static variable is created when class is loaded in to memory .
class sample 
{
public string s="hello";
public static string st="am static";
}
button click
{
sample obj=new sample();
obj.s;  //non static variable so can be accessed with object of class.
obj.st; // this is error. since static variable cannot be accessed with object of class.
sample.s; //this is error. since non static variable cannot be called with classname.variablename.
sample.st;// static variable can be accessed with classname.staticvariablename.
}

Static constructor:
1.Static constructor is executed only once when the class is loading in to the memory.
2.Static constructor can access only static variables.
class sample3
{
public string s="static constructor example";
public sample3() // normal constructor
{
MesssageBox.Show("Am from normal constructor");
}
static sample3() // static constructor
{
MessageBox.Show("Am from static constructor");
}
}
button click
{
sample3 obj=new sample3();
sample3 obj1=new sample3();
}

No comments:



Powered by Blogger.