Reputation: 193
how can you implement the Dispose method after using "using" on a MemoryStream object in a class that implements IDisposable?
public class ControlToByte :IDisposable
{
public static byte[] GetByte(object control)
{
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{ //do something here }
public void Dispose()
{
//how do you dispose of memorystream object?
}
Upvotes: 2
Views: 1000
Reputation: 223257
You don't have to implement IDispose
, nor do you have to call Dispose
explicitly. The using
block will ensure that, after completion, the MemoryStream
will be disposed. using
blocks actually work like try/finally
blocks. Something like:
{
System.IO.MemoryStream memoryStream = null;
try
{
memoryStream = new System.IO.MemoryStream();
//....your code
}
finally
{
if (memoryStream != null) //this check may be optmized away
memoryStream.Dispose();
}
}
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
In your current code, you are implementing IDisposable
on your class ControlToByte
, This would be useful if you want to dispose resourses in ControlToByte
. As illustrated, you don't need to implement IDisposable
for your class.
Upvotes: 6