When using unmanaged resources, what is the best practise for passing them to other objects? I understand it should be the responsibility of the class which creates the unmanaged resource to dispose of it, but does the resource persist if I pass it to a constructor, which then places it in a private field for use throughout the object's life.
For example, consider the following scenario:
public class Source
{
public static void Main(string[] args)
{
using (MyUnmanagedResource r = new MyUnmanagedResource())
{
Helper helper = new Helper(r);
helper.M1();
Helper helper2 = new Helper();
helper2.M2(r);
}
}
}
public class Helper
{
private MyUnmanagedResource resource;
public Helper(){}
public Helper(MyUnmanagedResource r)
{
resource = r;
}
public void M1()
{
Changer c = new Changer(resource);
c.M1();
}
public void M2(MyUnmanagedResource re)
{
Changer c = new Changer();
c.M2(re);
}
}
public class Changer
{
private MyUnmanagedResource resource;
public Changer(){}
public Changer(MyUnmanagedResource r)
{
resource = r;
}
public void M1()
{
resource.DoThing();
}
public void M2(MyUnmanagedResource re)
{
re.DoThing2();
}
}
In this situation, which is the best practise? Passing it in to the private variable for use later is certainly easier to write, but does this cause issues with disposing of the resource? With just one method in this example, the latter seems better, but when you have 10-15 methods that use the resource, and other classes being invoked that need the resource too, it can get very messy.
I've had issues with memory leaks in the past, and i'm not sure if its the way I handle unmanaged resources. I changed the unmanaged resource to be passed by argument, but it lead to it being an argument in around 50 methods, which seemed a pain.