How can I select the good method (I have in the example below show 2 differents way that doesn’t work). I was using instead of a variable of type Object with a IF and IS to do the job but I am trying to avoid using Object and boxing/unboxing. So I thought that Generic could do the job but I am stuck here.
Here is a small snippet of code that illustrate my question:
class Program { static void Main(string[] args) { Parser p = new Parser(); ObjectType1 o1 = new ObjectType1(); p.execute(o1); Console.Read(); } } class Parser { public T execute<T>(T obj) { /* if (obj is ObjectType1) this.action((ObjectType1)obj); else if (obj is ObjectType2) this.action((ObjectType2)obj); */ this.action(obj); return obj; } private void action(ObjectType1 objectType1) { Console.WriteLine('1'); } private void action(ObjectType2 objectType2) { Console.WriteLine('2'); } } class ObjectType1 { } class ObjectType2 { }
Update
I do not want interface and class. Sorry. I knew that it’s not the goal of the question.
Casting with (ObjectType)obj doesn’t work but if you do :
if (obj is ObjectType1) this.action(obj as ObjectType1); else if (obj is ObjectType2) this.action(obj as ObjectType1);
it works… why?
And… I cannot overload for all type the execute method because this method is from an Interface. This is why all need to be called from this method.
No, you can’t do this. Generics don’t work like C++ templates – the generic method is compiled just once. The only information that the compiler can use for overload resolution is the information it knows about within the generic method, regardless of what code uses it.
As an example to show this, here’s a bit of code which may not work how you expect it to:
It’s hard to say the best way to proceed without knowing more about what you want to do.