List Generics and Casting


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
        throw new Exception("Not a recognized type");
By : Michael G


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

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?

You can use the GetGenericArguments method of type Type, something like this:

object[] templates = myObject.GetType().GetGenericArguments();

By : ema

This video can help you solving your question :)
By: admin