-4

I have a basic question regarding type casting.

class A { }
class B : A { }

B b = new B();
A a = (A)b;

In the above code whether type casting will occur?

    interface IA
    {
        void process();
    }

    class B : IA
    {
        #region IA Members

        void IA.process()
        {
            throw new NotImplementedException();
        }

        #endregion
        public void process() { }
    }

    B b = new B();
    b.process();
    ((IA)b).process();

In the above code whether type casting will occur?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LokiDil
  • 197
  • 1
  • 3
  • 13

2 Answers2

1

You are using explicit cast like (A)b in both cases. So type cast will happen in both cases. If explicit casting is removed, then in first case implicit cast will occur and second case will not have any casting as it is same as b.process().

Aditya
  • 116
  • 2
  • Thanx Aditya, Can you please brief on this whether the compiler will generate the appropriate Type Casting code to IL?? – LokiDil Dec 28 '11 at 12:00
  • For downcasting, only the reference is stored in the new variable. But for upcasting classcast instruction is generated. Also, in second case, the instruction generated is to directly call IA.process instead of any casting instructions. – Aditya Dec 28 '11 at 18:51
0

I recommend to you create a class converter to cast class A to class B.

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • Thanx Dmity,I would like to know how the compiler will behave on these occasions whether it will cast or just point the reference to it?? – LokiDil Dec 28 '11 at 11:55
  • Sorry, I don't know. But the manner as I said is the best solution. Yeah it needs time to write some code but each property of the class is under your control. – NoWar Dec 28 '11 at 12:02