Home > Software design >  Return information that my object implements IDisposable
Return information that my object implements IDisposable

Time:08-24

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?

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • c#
  • Related