The only type whose "struct-ness" would be a problem is that of bmp
; are you saying that is a struct? If so, it would seem highly unusual that a struct would implement a non-trivial IDisposable.Dispose()
method, but it's possible that the type is implemented as an "immutable" struct but encapsulates a mutable reference and behaves like one. In that case, I would suggest something like:
var bmp = Surface.FromBmp("smile.bmp");
try
{
tex = Texture.FromSurface(ref rend, ref bmp);
}
bmp.Dispose(); // Or whatever method it exposes for such purpose
If the type in question actually requires disposal, it should expose a method for such purpose (some structure types like List<T>.Enumerator
implement IDisposable
because they are required to implement the interface, not because instances require cleanup). Do not cast to IDisposable
, since that will create a new boxed instance of the structure; the cost of that will significantly exceed the cost of creating another struct instance. Another pattern you might be able to use would be:
var bmp = Surface.FromBmp("smile.bmp");
using(bmp)
{
tex = Texture.FromSurface(ref rend, ref bmp);
}
since I think that form of the using
statement creates its own private copy of its argument and will let you do what you like with the original, but there's no real reason why it should be necessary to have code make the extra copy of bmp
, so I wouldn't particularly recommend that form. If for whatever reason bmp
requires cleanup but does not expose any method for that purpose other than via IDisposable
, you could do something like:
void CallDisposeOnRef<T>(ref T it) where T:IDisposable { it.Dispose(); }
and replace the last line of my first example with CallDisposeOnRef(ref bmp);
, which would avoid having to make an extra copy of bmp
in any fashion (the name is verbose to make clear that it only calls Dispose
on the target; some people might expect such a method that takes a ref
parameter to also set its argument to null
)