In C#, if you try to print a non-static variable from static method, you will see the reference error message.
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@
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@
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceConsoleApp3.Oops.ClassesAnbObjects
{
classCar
{
string color = "red";
staticvoidMain(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.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceConsoleApp3.Oops.ClassesAnbObjects
{
classCar
{
string color = "red";
staticvoidMain(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