Ask the Expert

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

I'm new to .NET and I can't seem to get the weird property syntax right. Can VS.NET help?
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.

This was first published in October 2002

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: