My Software Notes

Useful things I discover

C# 3.0 Properties

leave a comment »

Don’t you just love the new Property syntax in C# 3.0?  I got so tired of having to create a private class level variable and then click on the “Refactor”, encapsulate the variable, then cut and paste the generated code to the place in my code where I wanted it.

Now I just type:

public string MyProperty { get; set; }

and I’m done!

In case you didn’t know you can also specify the access modifier for the “get” or” set”:

public string MyProperty { get; private set; }

That way you can treat the “set” like a private class level variable and to the outside world the property looks read only. Or make it “protected” and only child classes can “set” it.

This works because the “get” and “set” are implemented as separate methods in the IL that is generated when you build your app.

One other tip.  If you have created an Interface that contains a read-only property and you don’t want to have to implement a private class level variable to hold the value then you can add a private or protected “set” to the property.  Here’s an example:

public interface IMyContract
{
    string MyProperty {get; }
    //other stuff ...
}

public class MyClass : IMyContract
{
    public string MyProperty { get; private set; }
    //other stuff ...
}

This works for the same reason I gave above, i.e., the “get” and “set” are implemented as different methods in the IL so you have implemented the Interface with the “get” and then adding your own “set” doesn’t violate the Interface contract because it is a separate method.

Advertisements

Written by gsdwriter

March 4, 2009 at 6:46 pm

Posted in Languages

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: