List of generics and casting

I have two classes, Media and Container.

I have two lists List<Media>

andList<Container>

I am passing these lists to another function (one at a time);

it can be this or that;

What is the correct way to check the type of the list's "template" so that I can call the asssociated method depending on the type of the list?

or should I just try to cast on 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");

      

0


source to share


4 answers


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



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

+3


source


Actually, you need to do 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
}

      

+11


source


What David said.

But if it should go through the same function, the operator typeof

should help. Also, it looks like you have an architectural flaw. How does the Media class relate to the Container class? Is there some common interface used by both that they should implement?

+2


source


Well, it depends on what your "// do this" method is ... If it's a method that runs on a media or a Container object and does different things on the basis of which it is, then you should put that method in those classes ...

Declare an interface named ICanDoThis

public interface ICanDoThis { void DoThis(); }

      

make sure both Media and Container implement this interface

public class Media: ICanDoThis { // }
public class Container: ICanDoThis { // }

      

and then in your client code "other functions" you can

 public void OtherFunction(List<ICanDoThis> list)
 {
    foreach(ICanDoThis obj in list)
        obj.DoThis();
 }

      

And what it is ... This code will call the appropriate implementation in the Media Class or Container depending on the specific type of the actual object, without having to write code to distinguish between the two ...

0


source







All Articles