1

I have read many article regarding the static fields that

Static methods have no way of accessing fields that are instance fields, as instance fields only exist on instances of the type.

But we can create and access the instance fields inside the static class.

Please find below code,

class Program
{
    static void Main(string[] args)
    {
      
    }
}

class clsA
{
    
    int a = 1;

    // Static methods have no way of accessing fields that are instance fields, 
    // as instance fields only exist on instances of the type.
    public static void Method1Static()
    {
        // Here we can create and also access instance fields
        // which we have declared inside the static method
        int b = 1;

        // a = 2; We get an error when we try to access instance variable outside the static method
        // An object reference is required for the non-static field, method, or property
        
        Program pgm = new Program();
        // Here we can create and also access instance fields by creating the instance of the concrete class
        clsA obj = new clsA();
        obj.a = 1;
    }
}

Is that true "We can access the non static fields inside static method" ?

Another question If we declare class clsA as static class even at that time we are not getting any compilation error if we declare instance fields inside the static method?

Where I am getting wrong?

1 Answer 1

1

You cannot access instance fields of the class that the static method is part of, because a static method is not called on an instance of this class. If you create an instance of that class, you can access it's instance fields as normal.

Your b is not an instance field, it's a normal local variable.

The sentence you quoted just means that you cannot do what you tried in the line you commented out: you cannot access a without an instance. Non-static methods use this as the default instance, so you could access a by simply writing a = 17; which is equivalent to this.a = 17;

Sign up to request clarification or add additional context in comments.

3 Comments

I agree. Also, if you declare your class clsA as static, you can't instantiate it with the new keyword so that line will fail obviously.
Thanks nvoidgt, So you mean the instance field are the fields which are created using new variable(correct me if I am wrong). So, finally can we say if you have to access instance fields of any particular class in static method of non static class we have to create instance of that class?
No, instance fields are those variables declared inside a class, but not inside a method. The internet is really not a good medium to explain this, you may want to get a good OOP book and read the first chapters. Your local library will have some.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.