Sunday, June 30, 2013

What is Static function or method ?


a.cs
class zzz
{
static void Main()
{
yyy a;
a=new yyy();
a.abc();
yyy.pqr();
}
}
class yyy
{
public void abc()
{
System.Console.WriteLine("abc");
}
public static void pqr()
{
System.Console.WriteLine("pqr");
}
}

Output
abc
pqr

In this program we have two functions abc and pqr. It is of significance to note that the function pqr has the word static whereas abc does not. If you want to access the static function pqr you say yyy.pqr() and to access the non static function abc you say a.abc(); You can't do the reverse i.e. you cant say a.pqr() and yyy.abc().

a.cs
class zzz
{
static void Main()
{
yyy a;
a=new yyy();
yyy.abc();
a.pqr();
}
}
class yyy
{
public void abc()
{
System.Console.WriteLine("abc");
}
public static void pqr()
{
System.Console.WriteLine("pqr");
}
}

Compiler Error
a.cs(7,1): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.abc()'
a.cs(8,1): error CS0176: Static member 'yyy.pqr()' cannot be accessed with an instance reference; qualify it with a type name instead

The word 'static' implies 'free'. Static signifies that you can access a member or a function without creating an object.

Observe that the function Main in zzz is static. This is because we are not creating any object that looks like zzz. The crux is that if you don't want to use 'new' and yet use the function then you must make the function static.

In both cases a dot is used to reference the function. The only difference is that a static member belongs to the class and as such we don't need to create an object to access it. On the other hand, a non-static member, that is the default, can be accessed only via an object of the class. Thus WriteLine is a static function in Console as we did not create an object that looks like Console to access it.

No comments:

Post a Comment