Reputation: 6745
I have two classes: Media and Container.
I have two lists List<Media>
and List<Container>
I'm passing these lists to another function (one at a time);
it can be one or another;
what's the proper way to check for the "template" type of the list so i can call an asssociated method depending on the list type?
or should i just try casting to the List<> and put Try/Catch blocks around it ?
Object tagObj = mediaFlow1.BackButton.Tag;
if (tagObj == Media)
//do this
else if (tagObj == Container)
//do this
else
throw new Exception("Not a recognized type");
Upvotes: 0
Views: 428
Reputation: 146449
Well, it depends on what your "//do this" method is... If it's a method that operates on a Media, or a Container object, and does different things based on which it is, then you should put that method in those classes...
Declare an interface named ICanDoThis
public interface ICanDoThis { void DoThis(); }
make sure that both Media and Container implement that interface
public class Media: ICanDoThis { // }
public class Container: ICanDoThis { // }
and then, in your client code "other function" you can
public void OtherFunction(List<ICanDoThis> list)
{
foreach(ICanDoThis obj in list)
obj.DoThis();
}
And that's it... This code will call the appropriate implementation in either the Media Class or the Container class depending on what the concrete Type of the actual object is, without your having to write code to discriminate between them ...
Upvotes: 0
Reputation: 5773
You can use the GetGenericArguments method of type Type, something like this:
object[] templates = myObject.GetType().GetGenericArguments();
Upvotes: 3
Reputation: 415690
What David said.
But if this must go through the same function, the typeof
operator should help. Also, this sounds more like you have an architectural flaw. How is the Media class related to the Container class? Is there some common interface used by both that they should implement?
Upvotes: 2
Reputation: 110091
The proper thing to do is to have two overloads for this function, accepting each type:
public void MyMethod(List<Media> source)
{
//do stuff with a Media List
}
public void MyMethod(List<Container> source)
{
//do stuff with a Container List
}
Upvotes: 11