views:

267

answers:

4

Hello everyone.

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");
+10  A: 

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
}
David B
+2  A: 

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?

Joel Coehoorn
yes, it should share the same function -- it's an eventhandler
Michael G
+3  A: 

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

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

ema
A: 

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 ...

Charles Bretana
This won't work until .Net 4.0 comes out. Generic arguments don't yet know about inheritance.
Joel Coehoorn
I've done this before with a base class.. That's what the generic where: interface syntax is for... Are you saying that it doesn;t work for interface inheritance?
Charles Bretana
interface inheritance doesn't work: List<Media> does not inherit from List<ICanDoThis>. If OtherFunction was generic, you could restrict the accepted types to types that implement ICanDoThis and that would work.
David B
public void OtherFunction<T>(List<T> list) where T : ICanDoThis
Joel Coehoorn