0

One of the rules for implementing the Dispose method says:

Throw an ObjectDisposedException from instance methods on this type (other than Dispose) when resources are already disposed. This rule does not apply to the Dispose method because it should be callable multiple times without throwing an exception.

See: http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

Does this mean that if I want to implement properties correctly, I cannot use auto-implemented properties? Do I need properties that implement it like this one?

private bool _property; 
public bool Property
{
    get
    {
       if(disposed) throw new ObjectDisposedException("MyClass");
       return _property;
    }
    set
    {
       if(disposed) throw new ObjectDisposedException("MyClass");
       _property=value;
    }
}
CarenRose
  • 1,266
  • 1
  • 12
  • 24
Michal
  • 119
  • 2
  • 9

2 Answers2

2

Generally, properties should act like fields (little or no computation, return the same value over multiple calls if no other state has changed), so they don't need the full dispose check, but you should put checks on defined public methods in your class.

thecoop
  • 45,220
  • 19
  • 132
  • 189
  • I agree. When you're just returning primitive values, such as integers, booleans, Color: don't bother doing a full dispose check. However, when that property returns some object that cannot reasonably be used after it is disposed, do a full check. – Steven Feb 10 '10 at 11:22
1

It depends. Calling a disposed object is an edge condition so you usually won't want to sacrifice your object's efficiency during regular use by adding all those tests. The correct way to read the rule is:

If calling a disposed method on a Disposed would cause an exception or have unwanted consequences, throw an ObjectDisposedException

E.g. If the Dispose method of your class sets some field to null you should throw an ObjectDisposedException from methods/properties using that field instead of failing with a NullReferenceException.

Stephan
  • 41,764
  • 65
  • 238
  • 329