0

I want a ArrayList, where you can add Objects , which implements an Interface. Something like this:

ArrayList<Object implements Interface> list =
   new ArrayList<Object which implements a specific Interface>();

What is the correct syntax for this?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

1 Answers1

0

Just set the interface as the type of the generic. Here you go the code in C#:

interface IFoo {
    void foo();
}

class Foo1 : IFoo {
    public void foo() {
        Console.WriteLine("foo1");
    }
}

class Foo2 : IFoo {
    public void foo() {
        Console.WriteLine("foo2");
    }
}

class Program {
    public static void Main() {
        // IFoo type: any object implementing IFoo may go in
        List<IFoo> list = new List<IFoo>();
        list.Add(new Foo1());
        list.Add(new Foo2());
        foreach(IFoo obj in list) obj.foo(); // foo1, foo2
        Console.ReadKey();
    }
}
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169