I have a method which return an instance of resource class, how can use the "using" statement to avoid resource leak?
public ResourceClass method()
    {
        return  new ResourceClass ();
    }
I hope my question is clear. Thanks in advance
I have a method which return an instance of resource class, how can use the "using" statement to avoid resource leak?
public ResourceClass method()
    {
        return  new ResourceClass ();
    }
I hope my question is clear. Thanks in advance
 
    
    You can relegate the responsibility of disposing it to your caller by declaring your using block around the entire usage of the resource
public ResourceClass method()
{
    return new ResourceClass();
}
then
using(var s = method())
{
   //do something with s
}
 
    
    This is as simple as just utilising the method method to create the instance in your using statement:
public void YourMethod()
{
    using (ResourceClass Foo = method())
    {
        ...
    }
}
This will only work of course if ResourceClass implements IDisposable.  Otherwise, your program won't compile.
