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
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.
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With