What are the best practices for using .NET Properties?

I'm a little confused about how much I MUST do with properties. I heard that properties should always represent a boolean property of a class. Get and Set should almost never throw exceptions, with the exception of ArgumentOutOfRange. It's true? Is the following example completely 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 object access element or just change the _Registered private variable directly?

If you have further tips on using properties, please enable it! Thanks

+5
source share
7 answers

MSDN. Property vs Method.

, . , . , , -. , , ASP.NET.

+6

, .

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;
    }
}
+4

: , , , , " " ( ) , . , , (, , /etc ).

get, ... , , , , / .

+1

, , , , Accessor. , _Registered.

0

, , , , , . , / . , , , , . , , -, - .

public void Register()
{
  ...do some stuff...
  this.Registered = true;
}

public void Unregister()
{
  ...do some stuff...
  this.Registered = false;
}

public bool Registered { get; private set; }

, - , , . , . , , , , , , .

0

accessor/mutator, . , ( ) , , . , , .

, () , , .

0

, . - , , .:) : , .

  • , , , , .
  • , , .
  • It is enough to limit the set of calls for a specific thread, but if you do, it must be documented, and your object must either implement ISynchronizeInvokeor display a property Dispatcher.
  • Setters can perform at least the following exceptions:
    • An ArgumentException( ArgumentNullException, ArgumentOutOfRangeExceptionetc.)
    • InvalidOperationException
    • ObjectDisposedException
0
source

All Articles