Q. I'm new to .NET and I can't seem to get the weird property syntax right. Can VS.NET help?

Asked by reader. Answered by the Wonk on October 17, 2002

A.

Properties are strange beasts. They look like fields to the user of the class, but they’re implemented like methods. Of course, this combines the ease of syntax of fields with the flexibility of implementing methods, but C# syntax, while concise, is unintuitive. If you’re unfamiliar with properties, the following is the use and implementation of an integer property called Number:

 

class Foo {

    private int number = 42;

 

    // Number property implementation

    public int Number {

        get { return number; }

        set { number = value; }

    }

}

 

// Number property usage

Foo foo = new Foo();

foo.Number = 13;

Console.WriteLine("My lucky number= {0}", foo.Number);

 

Even once you get your head around the property syntax, you may still find it tedious. To save yourself some trouble, right-click on a class in the VS.NET Class View and choose Add->Add Property to get a little wizard that knows how to take the name and type of your property and turn it into a skeleton for you. There are other menu options for methods, properties and indexers, as well.

Feedback

I have feedback on this Ask The Wonk answer