Note that there are some explanatory texts on larger screens.

plurals
  1. POPlease help me understand polymorphism when using generics in c#
    primarykey
    data
    text
    <p>I am having a problem understanding how polymorphism works when using generics. As an example, I have defined the following program:</p> <pre><code>public interface IMyInterface { void MyMethod(); } public class MyClass : IMyInterface { public void MyMethod() { } } public class MyContainer&lt;T&gt; where T : IMyInterface { public IList&lt;T&gt; Contents; } </code></pre> <p>I can then do this, which works just fine:</p> <pre><code>MyContainer&lt;MyClass&gt; container = new MyContainer&lt;MyClass&gt;(); container.Contents.Add(new MyClass()); </code></pre> <p>I have many classes that implement MyInterface. I would like to write a method that can accept all MyContainer objects:</p> <pre><code>public void CallAllMethodsInContainer(MyContainer&lt;IMyInterface&gt; container) { foreach (IMyInterface myClass in container.Contents) { myClass.MyMethod(); } } </code></pre> <p>Now, I'd like to call this method.</p> <pre><code>MyContainer&lt;MyClass&gt; container = new MyContainer&lt;MyClass&gt;(); container.Contents.Add(new MyClass()); this.CallAllMethodsInContainer(container); </code></pre> <p>That didn't work. Surely, because MyClass implements IMyInterface, I should be able to just cast it?</p> <pre><code>MyContainer&lt;IMyInterface&gt; newContainer = (MyContainer&lt;IMyInterface&gt;)container; </code></pre> <p>That didn't work either. I can definitely cast a normal MyClass to IMyInterface:</p> <pre><code>MyClass newClass = new MyClass(); IMyInterface myInterface = (IMyInterface)newClass; </code></pre> <p>So, at least I haven't completely misunderstood that. I am unsure exactly how I am to write a method that accepts a generic collection of classes that conform to the same interface.</p> <p>I have a plan to completely hack around this problem if need be, but I would really prefer to do it properly.</p> <p>Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload