Wednesday, September 17, 2008

Static Methods in C#

If you have to access a method in a class from outer side, you could have two ways.  First one is create an object for the class which contains that method and using that object call the method.

public class A
{
public void GoodMorning()
{
// code;
}
}

public class B()
{
A objA = new A();
objA.GoodMorning();
}


  Second method is you can create the method using 'static' so that you dont need to create an object for the class. You can directly call the function like this:

public class B()
{
A.GoodMorning();
}

Restrictions on methods having static are:

a)  If you wish to use a variable in side the static method, which is declared outside the static method ie, within class; you must declare that variable as static. Otherwise it will not intake that variable inside the static method.

No comments: