I’m relatively new to C# so please bear with me.
I don’t know how to perform this operation more efficiently.
public static void Foo<T>(LinkedList<T> list)
{
foreach (Object o in list)
{
if (typeof(o) == typeof(MyClass1))
(MyClass1)o.DoSomething();
else if (typeof(o) == typeof(MyClass2))
(MyClass2)o.DoSomething();
...
}
}
I would like to do something like this, or something more efficient than what I am doing now. by efficient I mean that program will run faster.
public static void Foo<T>(LinkedList<T> list)
{
foreach (Object o in list)
{
o.DoSomething();
}
}
Thank you for your help.
You’re looking for a polymorphic behavior.
In this case, you can define your method to constraint
TtoBase, and then you are allowed to use the method defined againstBasebut implemented by each derived class.You generally do not want to resort to type checking inside methods, as you seem to have already realized. It’s not particularly about efficiency as it is about good programming practice. Each time you add a new class, you have to come back to the method and add yet another check, which violates all kinds of solid programming practices.