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.
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With