Search code examples
c#castingoperatorsextension-methods

How can I cast a class to an interface with a matching method signature in C#?


Let's say we have an interface IFoo that defines a single method with the signature: public void Bar(). We also have a class Baz that defines multiple methods, one of which has the same exact signature as IFoo.Bar. Baz does not implement IFoo and it cannot be edited directly (we can only add extensions). If we have an array IFoo[] that we want to iterate over and call the Bar method of each item, we could add any concrete class that implements IFoo. I'd like to also add Baz objects to this array as well. Ideally we could simply cast Bar to IFoo but the cast needs to be defined. So I have two questions:

  1. Is it possible to write a conversion operator to cast Baz to IFoo?
  2. Is it possible to defined this conversion operator as an extension of Baz?

Thank you.

I tried casting Baz to IFoo hoping that since they both contain identical Bar method signatures and IFoo does not implement any properties or methods not defined in Baz, they would be implicitly compatible. This led to Compiler Error CS0030. My current work around is to have two arrays one IFoo[] and one Baz[]. For project specific reasons this is not ideal.


Solution

  • You can build a wrapper class that implements IFoo and wraps a Baz instance. Together with an extension it is very userfriendly.

    public static class BazExtensions
    {
        class FooWrapper : IFoo
        {
            private readonly Baz _baz;
            public FooWrapper(Baz baz)
            {
                _baz = baz;
            }
            
            void IFoo.Bar() => _baz.Bar();
        }
        
        public static IFoo AsIFoo(this Baz baz) => new FooWrapper(baz);
    }
    

    To get from Baz[] to IFoo[] you use Linq

    IFoo[] fooArray = bazArray.Select(b => b.AsIFoo()).ToArray();
    

    example on dotnetfiddle