Monday, April 6, 2015

An object reference is required for the nonstatic field method or property in c#


In this Example : Don't make your method (GetObject) static. It doesn't need to be static and it prevents you from using any non-static properties (like testobj). 

However if you need a method to be static, than it should not call the non-static members directly. Because the non-static member variables of a class always belong to an object.

If a method is static than non static members / properties cannot be accessed directly. otherwise create an instance to access non-static members or make the members as static. Else it will throw an error saying "an object reference is required for the nonstatic field method or property in c#" 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1
{
    public class Singleton
    {
        protected static Singleton _obj;
        private Singleton()
        {

        }

        public static Singleton GetObject()
        {
            if (_obj == null)
            {
                _obj = new Singleton();
            }
            return _obj;
        }

        public void Print(string s)
        {
            Console.WriteLine(s);
        }
    }
}


If static is removed than it errors out as mentioned. Because it cannot access an instance variable.


No comments:

Post a Comment