Home > DeveloperSection > Blogs > Static Member

Static Member


C# C# 
Ratings:
0 Comment(s)
 1667  View(s)
Rate this:

Static Member

A C# class can contain both static and non-static members.When we declare a member with the help of the keyword static, it becomes astatic member. A static member belongs to the class rather than to the objectsof the class. Hence static members are also known as class members andnon-static members are knows as instance members.

Static Field:

Static field can be declared as follows by using the keywordstatic.

Class myclass

{

Public static int x;

Public static int y=20;

}

When we declare a static field inside a class, it can beinitialized with a value .All un-initialized static fields automatically getinitialized to their default values when the class is loaded first time.

The C# provides a special type of constructor knows asstatic constructor to initialize the static data member when the class isloaded at first time. Other static member functions, static constructor cannotaccess non-static members directly.

The name of a static constructor must be the name of theclass and even they don't have any return type. The static constructor cannottake any arguments. That means there is only one form of static constructor,without any arguments. It is not possible to overload a static constructor.

Static Member Function:

Inside a C# class, member functions can be declared asstatic. But a static member function can access only other static members. Theycan access non-static members only through an instance of class.

Example:

Class myclass

{

Private static int x=20;

Private static int y=40;

Public static void method()

{

Console.WriteLine(“{0},{1}”,x,y);

}

}

Class myclint

{

Public static void main()

{

Myclass.method();

}

}


Don't want to miss updates? Please click the below button!

Follow MindStick