Showing posts with label Static method. Show all posts
Showing posts with label Static method. Show all posts

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.


Monday, July 28, 2014

Static Method in C#

static public int Add(int x, int y)    { 
       int result = x + y;       return result;    }//END   Add
static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.
or you should create in instance of your Program class, and then call Add on this instance. Like so:
 Program prog = new Program()  prog.Add(5,10);
  
Example:

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

            Console.WriteLine("Enter operand 1");
            int a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter operand 2");
            int b = Convert.ToInt32(Console.ReadLine());
            //Program add1 = new Program();
           
           Console.WriteLine(Program.add(a,b)); 
            
        }

        static public int add(int x, int y)
        {
            int c = x + y;
            return c;

        }
    }
}