a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
public int i = 10;
}
Compiler Error
a.cs(5,26): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.i'
Why did we get an error? Think for thinking is the hardest work there is, which is probably the reason why so few engage in it. If you still haven't got it, let us enlighten you. The same rules for static apply to functions as well as variables. Hence we get the above error.
a.cs
class zzz
{
static void Main()
{
yyy a = new yyy();
yyy b = new yyy();
a.j = 11;
System.Console.WriteLine(a.j);
System.Console.WriteLine(b.j);
yyy.i = 30;
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
public static int i = 10;
public int j = 10;
}
Output
11
10
30
A static variable belongs to the class. Hence if we create a static variable i, no matter how many objects we create that look like yyy, there will be one and only one value of i as there is only one variable i created in memory. Thus we access a static variable by prefacing with the name of the class and not name of object. If the variable is non-static like j then we have to use the syntax as explained earlier i.e. name of object dot name of variable. Thus each time we create an object that looks like yyy we are creating a new/another copy of the variable j in memory. We now have two j's in memory one for a and another for b. Thus j is called an instance variable unlike i. When we change the variable j of a to 11, the j of b remain at 10.
Thus functions are created in memory only once, irrespective of the word static. If a class has no instance or non static variables then it makes no sense to create multiple instances of the object as there will be no way of distinguishing between the copies created.
No comments:
Post a Comment