I know that as a rule, we should implement IDisposable on types that contain instances of disposable objects (fields or properties). Now, does that also apply to classes containing methods that return a disposable object?
Real life example:
class MyClass
{
public Image GetImage()
{
using (var stream = new MemoryStream(byteArray))
using (var img = Image.FromStream(stream))
{
return new Bitmap(img);
}
}
}
If the answer is no, then what's the difference between the previous code and the following?
Read-only property instead of a method:
class MyClass
{
public Image Image
{
get
{
using (var stream = new MemoryStream(byteArray))
using (var img = Image.FromStream(stream))
{
return new Bitmap(img);
}
}
}
}
Your class doesn't retain the unmanaged object for itself. It returns the unmanaged object to the caller. The caller is responsible for the unmanaged object.
Your property likewise doesn't retain the unmanaged object for the instance of your class. A property implementation that would require your class to implement IDisposable would look like this:
class MyClass : IDisposable
{
public Image Image { get; }
public MyClass(byte[] byteArray)
{
using (var stream = new MemoryStream(byteArray))
using (var img = Image.FromStream(stream))
{
Image = new Bitmap(img);
}
}
public void Dispose() { ... }
public virtual void Dispose(bool disposing) { ... }
}
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