Tuesday 12 May 2020

C# : Error CS0120 An object reference is required for the non-static field, method, or property

In C#, if you try to print a non-static variable from static method, you will see the reference error message.


Severity Code Description Project File Line Suppression State
Error CS0120 An object reference is required for the non-static field, method, or property 'Car.color' ConsoleApp3 C:\Users\sadakar\source\repos\ConsoleApp3\ConsoleApp3\Oops\ClassesAnbObjects\Car.cs 15 N/A


I wanted to check this example both in C# and Core Java and so if you are wondering how the similar behavior appears in core  java , take a look at this example@


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3.Oops.ClassesAnbObjects
{
    class Car
    {
        string color = "red";
        static void Main(string[] args)
        {
            Car myObj = new Car();
            Console.WriteLine(color);

            Console.ReadLine();
        }
    }
}

Solution:
1) Create an Object
2) Call/print the non static variable using object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp3.Oops.ClassesAnbObjects
{
    class Car
    {
        string color = "red";
        static void Main(string[] args)
        {
            Car myObj = new Car();
            Console.WriteLine(myObj.color);

            Console.ReadLine();
        }
    }
}




References: 
https://stackoverflow.com/questions/498400/cs0120-an-object-reference-is-required-for-the-nonstatic-field-method-or-prop

No comments:

Post a Comment