Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

up-casting in C# and call a specific method based on the derived type

I have a couple of classes, all derived from the same base type.

class basetype{}
class TypeA : basetype{}
class TypeB : basetype{}
...

A number of them is stored in a list.

List<basetype> myObjects

As always, each of these types has to be handled differently. Now I have a couple of methods to handle them, and one method that takes the basetype as parameter.

HandleTypes(TypeA obj){}
HandleTypes(TypeB obj){}
HandleTypes(basetype obj)

currently, my HandleAllTypes looks like that:

string name = obj.GetType().Name
switch(name)
{
  case "TypeA":
    return HandleTypes(obj as TypeA);
  case "TypeB":
    return HandleTypes(obj as TypeB);
  ....
}

now this is crap. Is there a way like

HandleTypes(obj ?"as derived type"?)

Searched through MSDN and other sources, found nothing.

like image 596
Alexander Avatar asked Jul 27 '11 12:07

Alexander


People also ask

Is Upcasting safe in C++?

Upcasting is safe casting as compare to downcasting. It allows the public inheritance that implicitly cast the reference from one class to another without an explicit typecast.

What is downcasting and when it is used?

Downcasting is useful when the type of the value referenced by the Parent variable is known and often is used when passing a value as a parameter. In the below example, the method objectToString takes an Object parameter which is assumed to be of type String.

Why is Upcasting safe?

When we cast object only the reference type of the object is changed but not the actual object type. Upcasting is safe and it does not fail. We need to check the instance of the object when we downcast the object using instanceof operator or we might get ClassCastException.

What is Upcasting in programming?

Upcasting is the typecasting of a child object to a parent object. Upcasting can be done implicitly. Upcasting gives us the flexibility to access the parent class members but it is not possible to access all the child class members using this feature.


1 Answers

How about

HandleTypes( obj as dynamic );

?


I've used this a couple times when I had to deal with third-party classes. It also can be very helpful when there are a lot of derived classes.

You can easily check whether the handling function is implemented:

try {
   HandleTypes( obj as dynamic )
}
catch( RuntimeBinderException ex ) {
   // not implemented
}
like image 97
Bertrand Marron Avatar answered Nov 15 '22 02:11

Bertrand Marron