upcasting

Trying to understand how to do upcasting or explict/implict type conversions. For example

public class p{}

public class p1{}

class example{

public void tt(p i){

}

public void tt(p1 ii){

}

public void onEvent( object ev){

tt(ev);

}

}

The issue is tt calling any of the functions, the problem is ev is one of the type, the only way is to use if statements to check each type ie if (ev is p) else etc



Answer this question

upcasting

  • WXS123

    I'm fairly certain this would result in a compile error. In your onEvent method, the system has no way of knowing what might be coming as as the "ev" object. This could be a string, an int, or one of your p or p1 classes. As a result, this is not safe and should result in an error.

    To do this, you do indeed have to "upcast" your object to the appropriate type. For example:

    public void onEvent( object ev)
    {
    if (ev is p)
    tt(ev as p);
    else if (ev is p1)
    tt(ev as p1);
    else
    throw new ApplicationException("bad type");
    }

    This is now type safe, since no matter what type of object ev is, the code is predictable and does not result in some wacky behavior (which you get into in C or C++ in these sorts of situations).

    Hope that helps,

    Erik




  • upcasting