Sobes.tech
Junior — Middle

Can you show an example of how to use a declared class with the 'using' operator in code?

sobes.tech AI

Answer from AI

In C#, the using operator is often used for automatic disposal of resources that implement the IDisposable interface. Here's an example of using a class with the using statement:

class Resource : IDisposable
{
    public void DoWork()
    {
        Console.WriteLine("Working with resource");
    }

    public void Dispose()
    {
        Console.WriteLine("Resource disposed");
    }
}

// Usage
using (var resource = new Resource())
{
    resource.DoWork();
}
// Dispose() is automatically called on resource here

In this example, the resource object is created inside the using block, and after exiting the block, the Dispose() method is called, ensuring the resources are released.