none
Error: An object reference is required for the non-static field, method, or property RRS feed

  • Question

  • see my code

    class Program
        {
            static void Main(string[] args)
            {
                Foo.Go();
            }
        }
    
        public class Foo
        {
            public void Hello()
            {
                
            }
    
            public static void Go()
            {
                Hello();
            }
        }
    

    when i am trying to access non static method from static method then getting error called "An object reference is required for the non-static field, method, or property"

    anyone can tell me reason why it is not possible with good easy explanation. thanks


    Monday, October 24, 2016 7:48 PM

Answers

  • If a method is non-static, you need an instance (also called an "object reference") of the class to call it. If it is static, you just need the class name to call it. If we add some code to your Main method, it might become a little clearer.

        {
            static void Main(string[] args)
            {
                // The Go method is static, so we just call it using the class name.
                Foo.Go();
    
                // But the Hello method is non-static, so we need an instance.
                Foo anInstance = new Foo();
                anInstance.Hello();
            }
        }

    The Go method itself does not have an instance, so it cannot call Hello. However, it could call Hello if we give it an instance.

    class Program
        {
            static void Main(string[] args)
            {
                // Create an instance.
                Foo anInstance = new Foo();
    
                // Now pass that instance to Go.
                Foo.Go(anInstance);
            }
        }
    
        public class Foo
        {
            public void Hello()
            {
                
            }
    
            public static void Go(Foo anInstance)
            {
                // Now we can call Hello using the instance passed in.
                anInstance.Hello();
            }
        }

    The concept of static versus non-static is a tricky one. A lot of beginners have trouble with it (including me, I admit). But if you keep thinking about it, eventually it should become clear.

    The key point is that static means it applies to the class as a whole, non-static applies to just one instance of the class.


    • Edited by Ante Meridian Monday, October 24, 2016 10:25 PM typo.
    • Proposed as answer by russhwalker Monday, October 24, 2016 10:56 PM
    • Marked as answer by Sudip_inn Tuesday, October 25, 2016 12:38 PM
    Monday, October 24, 2016 10:23 PM