Search code examples
c#interfaceinterface-design

How can I express that an argument needs to implement multiple interfaces in C#


Similiar to this question: How can I require a method argument to implement multiple interfaces? I want a method argument to implement several interfaces.

The interfaces shall be combinable in arbitrary fashion and I don't want to create an interface for each valid combination.

Think of a file. It can be:

  1. readable => IReadable
  2. writeable => IWriteable
  3. an archive => IArchive
  4. automatically generated => IGenerated

...

If I want to express that an argument needs to be an writable, generated archive I don't want to generate IWritableGeneratedArchive since there are too combinations and I want to use it with some existing classes I cannot modify.

Pseudocode:

void WriteTo( IWritable + IGenerated + IArchive file)
{
   //...
}

Solution

  • The solution I found here: How can I require a method argument to implement multiple interfaces? adjusted for C#.

    Credits go to Michael Myers

    internal interface IF1
    {
        void M1();
    }
    
    internal interface IF2
    {
        void M2();
    }
    
    internal class ClassImplementingIF1IF2 : IF1, IF2
    {
    
        public void M1()
        {
            throw new NotImplementedException();
        }
    
        public void M2()
        {
            throw new NotImplementedException();
        }
    
    }
    
    internal static class Test
    {
    
        public static void doIT<T>(T t) where T:IF1,IF2
        {
            t.M1();
            t.M2();
        }
    
        public static void test()
        {
            var c = new ClassImplementingIF1IF2();
            doIT(c);
        }
    }