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. ;)
Let's say we have an interface
interface iFoo {
void a();
}
Further I have for example 2 classes that implement this interface and the method that is in it:
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"); }
}
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:
namespace ExampleFooBar
{
class Program
{
static void Main(string[] args)
{
List<iFoo> fooBarObjects = new List<iFoo>();
fooBarObjects.Add(new bar1());
fooBarObjects.Add(new bar2());
for(int i = 0; i < 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()
}
}
}
}
}
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
if(fooBarObjects[i].GetType() == typeof(bar1))
{
fooBarObjects[i].anotherMethodBar1();
}
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:
- a()
- Equals()
- GetType()
- GetHashCode()
- ToString()
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.
Thanks a lot and best regards!