Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Implementing Static Member & Methods in C#

Static Members in C#
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 a static member A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members In C#, data fields, member functions, properties and events can be declared as static

Static Field
Static fields can be declared as follows by using the class MyClass keyword static.{
public static int x; public static int y = 20; }

Static Member Functions


Member functions can also be declared as static ,but a static member function can access only other static members. They can access non-static members only through an instance of the class. We can invoke a static member only through the name of the class

using System; class MyClass { private static int x = 20;

Static Member Functions

private static int y = 40; public static void Method() { Console.WriteLine("{0},{1}",x,y); } } class MyClient { public static void Main() { MyClass.Method(); } }

Static Properties The properties also in C# can be declared as static


The static properties are accessing using the class name.
class MyClass { public static int X { Get { Console.Write("GET"); return 10; } set { Console.Write("SET"); } } } class MyClient { public static void Main() { MyClass.X = 20; // calls setter displays SET int val = MyClass.X;// calls getter displays GET } }

You might also like