We know that If a class is made static, all the members inside the class have to be static; there cannot be any instance members inside a static class. If we try to do that, we get a compile time error.
But if have an instance member inside a static method, I do not get a compile time error.
public static class MyStaticClass
{
// cannot do this
//int i;
// can do this though.
static void MyStaticMethod()
{
int j;
}
}
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
public class MyStaticClass
{
static int j; //static member
int i;//instance member
static void MyStaticMethod()
{
i = 0; // you can't access that
j = 0; // you can access
}
}
Its not instance member, its (j
) a local variable inside a static method.
Consider following non-static class.
public class MyStaticClass
{
int i; //instance member
static void MyStaticMethod()
{
i = 0; // you can't access that
}
}
The above class has a instance member i
, you can't access that in a static method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With