-1

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

Ariel
  • 165
  • 1
  • 3
  • 15
  • 1
    Implement disposable pattern using `IDisposable` interface. – ZorgoZ Jan 02 '19 at 13:47
  • What is `ResourceClass`? This: https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.documents.resource?view=azure-dotnet ?? – Jamiec Jan 02 '19 at 13:47
  • Possible duplicate of [returning in the middle of a using block](https://stackoverflow.com/questions/662773/returning-in-the-middle-of-a-using-block) – thehennyy Jan 02 '19 at 13:48
  • ResourceClass is a class that implements IDisposable – Ariel Jan 02 '19 at 13:49
  • Possible duplicate of [How to create a list with different object type from json](https://stackoverflow.com/questions/54007364/how-to-create-a-list-with-different-object-type-from-json) – KoshVorlon Jan 02 '19 at 14:07

2 Answers2

2

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
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34
1

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.

Martin
  • 16,093
  • 1
  • 29
  • 48