Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello friends,

Why is an explicit cast required when you want to cast a derived type to a base type, In the sense :
Derived d = (Derived) Base;
But if i do vice versa nothing like this is required. Like below:
Base b = new Derived();


Thanks a ton,
Rahul
Posted
Comments
PIEBALDconsult 7-Jul-14 9:39am    
Because the derived class didn't implement an implicit conversion. The latter doesn't need it because Derived IS_A Base.

http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
Rahul VB 7-Jul-14 10:22am    
Thanks for expalanation

You are touching the subject of up- and down-casting. Let see some sample:
C#
public class MyBase
{
  public String Name;

  public virtual void Log( )
  {
    Console.WriteLine(String.Format("My name is {0}", Name));
  }
}

public class MyClassA : MyBase
{
  public int Size;

  public override void Log( )
  {
    base.Log();
    Console.WriteLine(String.Format("My size is {0}", Size));
  }
}

public class MyClassB : MyBase
{
  public int Color;

  public override void Log( )
  {
    base.Log();
    Console.WriteLine(String.Format("My color is {0}", Color));
  }
}

You can see that an instance of any of the derived classes always will contain a full version of the base class, so there is no need to tell the compiler how to cast it. It's called down-casting and always can be done without problem.
On the other side a reference to a base class can hold reference to an actual instance of MyBase, NyClassA or MyClassB too, so if you want to assign it to MyClassA you have to tell the compiler that you know what are you talking about - this called up-casting and must be explicitly stated...
 
Share this answer
 
Comments
Rahul VB 7-Jul-14 10:20am    
Very nice explanation Sir,
Thanks a Ton,
Rahul
Sergey Alexandrovich Kryukov 7-Jul-14 10:49am    
5ed.
I added my explanation from a bit different point of view, please see Solution 3.
—SA
Maciej Los 7-Jul-14 15:45pm    
Nice, +5!
Rahul VB 8-Jul-14 0:51am    
Hello Sir,

Ok, what you mean to say is that :
MyBase mb = new MyClassA() /// works fine because i know that MyClassA is a full version of the base class.
But,
MyClassA mca = (MyClassA)MyBase();////this is because the base might be assigned an object of lets say MyClassB and hence i will do explicit casting so as to extract the object which i want to.

Am i correct?

Thanks a Ton,
Rahul
Kornfeld Eliyahu Peter 8-Jul-14 3:28am    
The first part you got right.
The problem with the second part is that the compiler does not know what the run-time type will be of MyBase, so it can not accept the assignment operator. When you casting it you explicitly tell the compiler that at the run-time it will be MyClassA and not other. If it will be something else you will be in trouble of course...
To add to the Solutions 1 and 2:

The reason for these casting rule is some extra members added to the derived class. Consider this:
C#
class Base {
    internal int A { get; set; }
}

class Derived : Base {
    internal int B { get; set; }
}

class AnotherDerived : Base { }


As you understand, there are instance properties Base.A, Derived.A, AnotherDerived.A and Derived.B. And, importantly, no AnotherDerived.B.

Imaging, for example, that you could have successful assignment
C#
// will not compile:
Derived derived = new AnotherDerived(); 
// it would give you access to derived.B:
derived.B = 13; // disaster: access to non-existing member


It would give you access to derived.B, which is, in turn, would be the access to non-existing member, because runtime type is actually AnotherDerived. That's why the dynamic cast is used:
C#
Base @object = new //... something

//...

Derived derived = @object as Derived;
if (derived != null) // otherwise B does not exist
   derived.B = 15;

Note that the actual use of dynamic type check and casting, being a part of OOP, is considered as violation of OOP. Indeed, if you have such need, it suggests that the object hierarchy is not reasonably planned. There are rare reasonable exclusions though. They are only reasonable when they are rare. Your code should not be fundamentally based on it.

See also:
http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx[^],
http://msdn.microsoft.com/en-us/library/scekt9xw.aspx[^].

—SA
 
Share this answer
 
v3
Comments
Rahul VB 7-Jul-14 13:53pm    
Thanks a Ton,
Nice explanation.
Sergey Alexandrovich Kryukov 7-Jul-14 15:08pm    
You are very welcome.
Then will you accept it formally, too? You can always accept more than one answer.
—SA
Rahul VB 8-Jul-14 0:02am    
Accepted
Maciej Los 7-Jul-14 15:46pm    
5!
Sergey Alexandrovich Kryukov 7-Jul-14 17:56pm    
Thank you, Maciej.
—SA
Makes not much sense to ask such questions here - better read a book about Basic OOP concepts and C# (maybe also interesting covariance vs. contravariance- )http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx[^]

But a quick answer: An instance of a derived type "IS" always also an instance of the base type. So for the "type engine" this always works because there is only one valid "path" to the base class (all derived classes are also valid instances of their base class, so a cast could NEVER fail - and isn't needed therefore). But for the opposite case, how should the type engine know that the instance of your base type is exactly of the derived type - there could be many derived types for a given base type - so explicit casting is needed (and may fail).
 
Share this answer
 
Comments
Rahul VB 7-Jul-14 10:21am    
Yes Sir,

I understand, however i started reading a book and encountered a doubt hence i thought of asking.

Thanks a ton,
Rahul
Sergey Alexandrovich Kryukov 7-Jul-14 10:47am    
All correct, a 5.
I would also explains the terms "up-casting" and "down-casting".
—SA
Rahul VB 7-Jul-14 13:53pm    
Thanks a lot,
Nice explanation
Sergey Alexandrovich Kryukov 7-Jul-14 11:05am    
I added my explanation from a bit different point of view, please see Solution 3.
—SA
Maciej Los 7-Jul-14 15:45pm    
Agree, a5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900