Static fields question
Question
im trying to understand the get and set properties for fields, and run in to this issue, can somone explaine to me why i had to make the int X field Static to make this work?
using System;
namespace ConsoleApplication1
{
class Program
{
public static int X = 30;
public static void Main()
{
var cX = new testme();
cX.intX = 12;
Console.WriteLine(cX.intX);
cX.intX = X;
Console.WriteLine(cX.intX);
Console.ReadKey();
}
}
class testme
{
public int intX
{
get;
set;
}
}
}
Solution
Because you were using the field in a static context, in this case the method public
static
void Main
. Since your Program
class just runs statically there is no instance and therefore you can't access any instance members.
OTHER TIPS
because it is used in a static method
Since Main
is static, you cannot access non-static instances from outside of it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow