If you have 40 properties in one class, you probably have a design problem, but the transition ... It really depends on the specific use case, but you should just throw an ObjectDisposedException if the property cannot actually be resolved, because the class has been deleted. To give a concrete example:
public class MyStream : IDisposable { private string name; private Stream stream; public MyStream(string name) { this.Name = name; this.Stream = new FileStream(...); } public string Name { get { return this.name; } } public Stream Stream { get { if (this.IsDisposed) { throw new ObjectDisposedException(); } return this.stream; } } private bool IsDisposed { get; set; } public void Dispose() { if (!this.IsDisposed) { this.IsDisposed = true; this.Stream.Dispose(); this.Stream = null; } } }
Here, the Stream property throws an exception because the main stream has been deleted, so it can no longer be used. But Name has no reason to quit. From there, in many cases, you can decompose your code so that access to the actual problematic property throws an exception:
public int Length { get {
If you still have too many properties to decorate even after this template, you can use libraries like Fody , which allows you to enter compile-time behavior. Using it, you can make the [ThrowIfDisposed] attribute, which you apply to the properties as needed.
source share