tags:

views:

168

answers:

2

Hi All, I have one doubt regarding casting.

  public void Test(out T a, out T b)
    {

        object d,e;
        d = 10;
        e = 35;
        Console.WriteLine(d.GetType());
        a = (T)d;

        b = (T)e;

    }

Here d.getType() will return System.int32. so my question is why cant we directly code something like a=(T)10; I am not getting it properly.pls help. Thanks.

+8  A: 

Casting doesn't work that way. T needs to be either a subclass or a superclass of System.int32 for casting to work without any additional operator overloading.

I'm assuming T is a wrapper of some kind for an int. You need to make a function or constructor to convert int to T. That's not the same thing as casting.

You can define your own explicit operator that will do this conversion for you, and the syntax will be the same as what you have. But you still have to define the conversion yourself.

Something like this:

public static explicit operator T (int original) {
    T t = new T();
    t.value = original;
    return t;
}
Welbog
Ok,I got the point."T needs to be either a subclass or a superclass of System.int32 for casting to work."..thats the key .thats why object works as it is the base of all.correct me if I am wrong.Thanks for teh help.
Wondering
+2  A: 

Assuming this is for a generic class with type T, the question is why does it fail one way and not the other?

As d is an object, (T)d represents an unboxing operation rather than a cast. Unboxing is done at runtime and thus survive compilation. I imagine if type T is anything other than an int then this step will fail during runtime.

On the other hand, (T)10 is a casting operation - which is type-checked at compile-time. If you do not have a cast operator between T and int (as described in Welbog's answer) then this cannot compile.

Joel Goodwin
yes its int..anything other than int will throw an Invalid cast exception. BTW is there ant rule of thumb to decide between up-down casting and box-unboxing? AFAIK boxing, unboxing denotes conversion of value-->ref and ref->value..and up-downcasting generally works with base class and subclass, like upcasting can be done easily but for downcasting we need to declare it explicitly.Thanks
Wondering
As d was an Object then d=10 and (T)d represented boxing and unboxing. If d was anything other than an Object, it would have been a cast.
Joel Goodwin