Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not have instance members in a static class but I can have instance members in a static methods?

Tags:

c#

.net

oop

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;
        }
    }
like image 228
Kunal Nair Avatar asked Sep 14 '25 15:09

Kunal Nair


2 Answers

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 
    }
}
like image 138
Thilina H Avatar answered Sep 16 '25 06:09

Thilina H


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.

like image 33
Habib Avatar answered Sep 16 '25 05:09

Habib