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");
source to share
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 ...
source to share