title: C# list of interface objects - casting single elements
body: <p>I have a C# problem that has been bothering me for the past couple of days. I'll try to explain it based on an abstract description of what I am doing. Hope it is easy to follow. ;)</p>
  
  <p>Let's say we have an interface</p>
  
  <pre><code>interface iFoo {
     void a();
  }
  </code></pre>
  
  <p>Further I have for example 2 classes that implement this interface and the method that is in it:</p>
  
  <pre><code>class bar1 : iFoo
  {
     public void a() { Console.WriteLine("bar1"); }
     public void anotherMethodBar1() { Console.Write("I love "); }
  }
  
  class bar2 : iFoo
  {
     public void a() { Console.WriteLine("bar2"); }
     public void anotherMethodBar2() { Console.Write("beer"); }
  }
  </code></pre>
  
  <p>Each class also provides an additional unique method - anotherMethodBar1() and anotherMethodBar2(). Now in my main() I want to create a list, which contains objects that implement my interface like this:</p>
  
  <pre><code>namespace ExampleFooBar
  {
      class Program
      {
          static void Main(string[] args)
          {
              List&lt;iFoo&gt; fooBarObjects = new List&lt;iFoo&gt;();
              fooBarObjects.Add(new bar1());
              fooBarObjects.Add(new bar2());
  
              for(int i = 0; i &lt; fooBarObjects.Count; i++)
              {
                  if(fooBarObjects[i].GetType() == typeof(bar1))
                  {
                      //Cast element to bar1 and use anotherMethodBar1()
                  }
                  if(fooBarObjects[i].GetType() == typeof(bar2))
                  {
                      //Cast element to bar2 and use anotherMethodBar2()
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p>As you can see I want to call each object's own (not included in the interface) method (based on the class we have anotherMethodBar1() or anotherMethodBar2(), which are NOT part of the interface). The question is - how do I do that? I'm new to C# and so far my experience had little to do with casting but right now I need it. Is this even done by using casting or is there another way? It is not possible to simply call the method</p>
  
  <pre><code>if(fooBarObjects[i].GetType() == typeof(bar1))
  {
      fooBarObjects[i].anotherMethodBar1();
  }
  </code></pre>
  
  <p>because C# doesn't understand the exact type that lies underneath and thus the available methods/functions for this object are only the standard once plus my a()-method:</p>
  
  <ul>
  <li>a()</li>
  <li>Equals()</li>
  <li>GetType()</li>
  <li>GetHashCode()</li>
  <li>ToString()</li>
  </ul>
  
  <p>I really tried to find a solution but so far only the inverse has been asked quite often - list of objects to a list of interface conversion.</p>
  
  <p>Thanks a lot and best regards!</p>