-1

I'm working on some project and I have situation where I need to create a list that would accept classes which implement at least one interface. It should look like this:

interface A
{
    void foo();
}
interface B
{
    void bar();
}

class C : A, B
{
    public void foo()
    {
        // Do some stuff specific for A
    }
    public void bar()
    {
        // Do some other stuff for B
    }
}
class D : B
{
    public void bar()
    {
        // Do some actions for B
    }
}
class E : A
{
    public void foo()
    {
        // Do something specific for A
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<A+B> list = new List<A+B>();

        list.Add(new C());
        list.Add(new D());
        list.Add(new E());

        foreach (A a in list)
        {
            a.foo();
        }
        foreach (B b in list)
        {
            b.bar();
        }
    }
}

Edit:
List<object> doesn't really fits because I need to hold classes with interfaces A and B and execute specific logic for each interface.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Psyhich
  • 47
  • 6

2 Answers2

0

Is a type implementing an interface?

To determine whether this is the case, you can use the Type.GetInterfaces method. It returns a Type[] array of all the interfaces implemented by a type. Example taken from docs:

using System;
using System.Collections.Generic;

public class Example
{
    static void Main()
    {
        Console.WriteLine("\r\nInterfaces implemented by Dictionary<int, string>:\r\n");

        foreach (Type tinterface in typeof(Dictionary<int, string>).GetInterfaces())
        {
            Console.WriteLine(tinterface.ToString());
        }

        //Console.ReadLine()      // Uncomment this line for Visual Studio.
    }
}

/* This example produces output similar to the following:

Interfaces implemented by Dictionary<int, string>:

System.Collections.Generic.IDictionary`2[System.Int32,System.String]
System.Collections.Generic.ICollection`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.Int32,System.String]]
System.Collection.IEnumerable
System.Collection.IDictionary
System.Collection.ICollection
System.Runtime.Serialization.ISerializable
System.Runtime.Serialization.IDeserializationCallback
 */

How to get the type of an object:

myObject.GetType()

How to create a List with objects implementing interfaces

You can derive the Add from IList and implement it, see How do I override List<T>'s Add method in C#? for example. In your case, you would need to check whether the type of the object implements an interface.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
-1

Thanks to guys in comments I created interface Base that is inherited both by A and B and used list with it

Psyhich
  • 47
  • 6