kosnkov
kosnkov

Reputation: 5941

Return information that my object implements IDisposable

I have this class

public class MyClient : IMyClient, IMyClientAsync,IDisposable

I am writing a wrapper that returns IMyClientAsync like this:

IMyClientAsync GetClient()
{
   return new MyClient ();
}

But then anyone who is using this wrapper can't close the client in a using block like using(var client = MyWrapper.GetClient()){} since the information that object implements IDisposable is lost.

Is there any way to change it to be able to still close my client in a using block?

Upvotes: 1

Views: 72

Answers (2)

lee-m
lee-m

Reputation: 2267

It is possible for interfaces to inherit from other interfaces, so rather than having MyClient inherit both IMyClientAsync and IDisposable, simply change IMyClientAsync to inherit from IDisposable instead like so:

public interface IMyClientAsync : IDisposable
{}

public class MyClient : IMyClient, IMyClientAsync
{}

This way, consumers of your code can wrap instances of IMyClientAsync in a using block since the compiler knows it implements IDisposable.

Upvotes: 8

Ibrennan208
Ibrennan208

Reputation: 1402

IMyClientAsync GetClient()
{
   return new MyClient ();
}

Would need to be:

MyClient GetClient()
{
   return new MyClient ();
}

In order for the compiler to know it implements IDisposable.

As you have it in your question, IMyClientAsync does not implement IDisposable.

If that is not possible for your use case, you could also ensure your IMyClientAsync interface also implements IDisposable.

Upvotes: 1

Related Questions