#791 – Properties Are Not Variables

A property cannot be used in the same way as a variable, like a field can.

A field is a variable that is defined within a class and it denotes an actual storage location.  Because it refers to a storage location, you can pass a field by reference, using a ref or out keyword on the argument.

If Name is a public field of a Dog class, you can do this:

        static void Main(string[] args)
        {
            Dog d = new Dog("Bob");

            MakeNoble(ref d.Name);
        }

        private static void MakeNoble(ref string name)
        {
            name = "Sir " + name;
        }

A property, on the other hand, is not a variable and its name does not refer directly to a storage location.  So you can’t pass a property as a ref or out argument to a method.

            Dog d = new Dog("Bob");
            d.Age = 5;
            AgeMe(ref d.Age);  // Compile-time Error

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment