Steven Nagy .NET

Wednesday, 22 August 2007

Properties in .Net 3.5 - Updated!

Note: This article was updated, see "Amendment" at bottom.

When writing properties previously, you might do something like this:

private string _name;
public string Name
{
        get { return _name; }
        set { _name = value; }
}

(Note: the reasons for using a property over just a public field can vary; components need properties for design time support for example)

Well now you can short hand this in .Net 3.5 as follows:


public string Name { get; set; }

This is neat. At first it might confuse you... "I'm not going to inherit from this class!". You can also do this:

 

public string Name { get; private set; }

Which means your class can have a public getter but can only be set internally. If you only ever want your class to change the value and have external classes only querying the value, this works great.

However, the problem I ran up against today was that I had a base abstract class that I was inheriting from. I only wanted the sub classes to have getters, and have the ability to set the value privately.


public abstract string Name { get; }

I still wanted the implementing class to be able to privately set the value. However, this causes a build error:

public override string Name { get; private set; }

This is because I can not implement a setter in an override (the abstract declaration dictates the contract, and that was for a getter only). So, I had no option but to implement the old method of having a private setter:

private string _name;
public override string Name
{
    get { return _name; }
}

And then just set the _name field privately. Naturally its no big deal because without the new shortcut code I still would have had to implement it this way, but it would be nicer visually if I could have found a way to do it in one line.

AMENDMENT!

A co-worker suggested the following, which I tested and works great:

public abstract class test
{
    public abstract string Name { get; protected set; }
}

public class Tester : test
{
    public override string Name { get; protected set; }
}

This means you can maintain the easy read syntax. Happy days!

 

Technorati Tags: , ,


 

 


 

0 Comments:

Post a Comment



<< Home