views:

81

answers:

3

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;
        }
    }
}
+4  A: 

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.

Joey
ah oki i get it, thx for the explanation
Darkmage
A: 

because it is used in a static method

mfeingold
A: 

Since Main is static, you cannot access non-static instances from outside of it.

David Hedlund
Sure you can. Accessibility and staticness have nothing to do with each other.
Eric Lippert