Understanding Static keyword in C#

Static keyword can be applied to
Class, field, method, properties, operator, event and constructors.
Static member belongs to the class and not to any object of the class.
They can be used without creating the instance of the class.

For e.g. Static Void Main()
It is called by the operating system on program execution
To access the static member we’ll use


When a variable is declared as static internally what happens is that all the instances of the class share the same static variable. A static variable is initialized when its class is loaded. If not
initialized explicitly then
it is initialized to zero for numeric variable
null in case of object references
false for boolean

StaticMethod they can only contain static member and call other static method.
If we need to access them than it can be done through the object of that class

class Game
string getGameName()
public static void getNameThroughStatic(Game g)
g.getGameName(); // accessing static method

When to use them?
Well we can use them when we need to maintain information applicable to the entire class

suppose we have a class Employees there we can have a static count variable to keep track of no of employees.

class Employees
static in count=0;
public Employees()



What are Static Constructor?
They can be used to initialize the static variables.
They are called automatically and before the instance constructor (if called any).

for above class
static Employees() // no other access modifiers for them

What are static Classes?
A class whose objects can’t be created and which can only have static members. They can’t be inherited as well.
They can have static constructor

Why use static Classes?
It can be used to group related static method.


Dynamically adding rows and columns to Grid View

Hi to add rows and columns to Gridveiw dynamically what
we will do is that

1) Create a DataTable object to which than we will bind the GridView
DataTable dt=new DataTable();

2) IF you need two columns than create two DataColumn object
DataColumn dCol1=new DataColumn(FirstC, typeof(System.String)); // string FirstC=”column1″
DataColumn dCol2=new DataColumn(SecondC, typeof(System.String)); // string SecondC=”column2″

Add it to the table


3)Run the loop for as many rows you want to add.

// say you want to add two rows

for(int i=0;i<2;i++)
DataRow row1 = dt.NewRow();
row1 [FirstC] = “One”;
row1 [SecondC] =”Two”
dt.Rows.Add(row1 );


Now iterate through each datacolumn and create a BoundField foreach column

foreach (DataColumn col in dt.Columns)
BoundField bField = new BoundField
bField.DataField = col.ColumnName;
bField.HeaderText = col.ColumnName;
GridView1.DataSource = dt;
//Bind the datatable with the GridView.