Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice for using .NET Properties?

I am a little confused about how much I SHOULD do with properties. I have heard that properties should always represent a logical property of the class. Get and Set should almost never throw exceptions with the exception of ArgumentOutOfRange. Is that true? Is the following example totally wrong?

public bool DeviceRegistered
{
    get{ return _Registered;}
    set
    {
        if(value)
        {
            RegisterDevice();
            _Registered = true;
        }
        else
        {
            UnRegisterDevice();
            _Registered = false;
        }
    }
}

Also, If a method in the same class wants to change the value of a property should it go through the set accessor of the property or just modify the private variable _Registered directly?

If you have any additional advice when using properties please include! Thanks

like image 885
PICyourBrain Avatar asked Feb 25 '10 15:02

PICyourBrain


3 Answers

Here is a link to the Design Guidelines for properties from the MSDN. Make special note of the Property vs Method section.

From my own personal experience, you shouldn't use properties to do a lot of work. They should be returning information that has already been retrieved. I'm currently working on a code base which has a lot of lazy loaded properties that retrieve information from a web service. Looking at the properties of a class while debugging causes all of the properties to be evaluated, causing functional evaluation to time out and the ASP.NET process to crash.

like image 97
Richard Nienaber Avatar answered Sep 21 '22 10:09

Richard Nienaber


In this case I think it is more logical to use methods because you are performing an action.

private volatile bool _DeviceRegistered;
private readonly object _Lock = new object();

public bool DeviceRegistered
{
    get { return _DeviceRegistered; }
}

public void RegisterDevice()
{
    lock (_Lock) // A good idea to lock
    {
        // ........
        _DeviceRegistered = true;
    }
}

public void UnregisterDevice()
{
    lock (_Lock)
    {
        // ........
        _DeviceRegistered = false;
    }
}
like image 28
ChaosPandion Avatar answered Sep 22 '22 10:09

ChaosPandion


A narrow answer: I like using read-only properties when I've got a value that takes a bit of work to get, but that I want the "rest of the world" (even callers inside the same class) to think of as a variable whose value is just always available. The property will do the work to get the value and then simply return (perhaps with optimizations like caching/etc).

The alternative would be a "get" method, and that's fine... but I like using a property when I don't want the caller burdened with the idea that there's work involved in fetching/figuring the value.

like image 26
lance Avatar answered Sep 22 '22 10:09

lance