Programming Languages

C# using Statements: Who Owns Closing the Resource?

Huwell Consultancy editorial2 min read

A C# object that implements IDisposable may own a resource that needs a clear end of use. A using statement helps express that lifetime. It is different from a using directive that imports a namespace.

Read a small file with a clear lifetime

using (var reader = File.OpenText("example.txt"))
{
    Console.WriteLine(reader.ReadLine());
}

The reader is disposed when control leaves this block, including when an exception occurs inside it. Microsoft’s language reference explains this behaviour. The example assumes the file exists and does not include the surrounding error handling an application may need.

Know when a declaration ends

A using declaration without braces disposes the local resource at the end of its enclosing scope. That can be a different point from the end of a smaller using block. Choose a lifetime that matches the work rather than keeping a resource open longer by accident.

Ask who owns the object

If a method receives a resource created by its caller, do not assume the method should dispose it. Agree ownership. A helper that closes an object the caller still expects to use can create a difficult failure. The resource’s contract and the surrounding design matter.

Practice questions

  • Where does the resource stop being used?
  • What happens if reading fails?
  • Can code outside the block still try to use it?
  • Who is responsible for disposal when ownership is shared?

For a .NET interview in Malta, explain the lifetime in plain language before discussing syntax. The useful skill is making ownership clear, not adding using everywhere.

Sources and further reading

Explore current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision