How to "cast" base class into inheriting class??

cast , inheritance , encapsulation Huddersfield, United Kingdom
  • 12 years ago
    C# Scenario: I have a base class called RawClass and an inheriting class called RichClass. RichClass inherits from RawClass like this: public class RichClass : RawClass. I have an instance of RawClass, which I would like to cast to type RichClass. This doesn't work: RichClass richClass = (RawClass)rawClass; How can I instantiate the RichClass from RawClass? Or do I have to use encapsulation rather than inheritence? Cheers, David
  • 12 years ago
    David, You can't cast variables of the base class into the type of a sub class, because the sub class extends the base class. You can do it the other way round. You can't instantiate one class from another, but you can use a RichClass variable anywhere that expects a RawClass. Also the purpose of doing the cast is to get the expression to be the same type as the variable, which is why your line of code doesn't work. So you can do: RichClass rc; RawClass wc; wc = (RawClass) rc; I don't have a compiler at home and I don't usually write C#, so I'm not sure if you can do the assignment without the cast - it may depend on the compiler options. I'm sure someone else can chip in. Regards Andy
  • 12 years ago
    Cheers, Andy. Yeah, it's obvious when you point it out. There is a new feature in the .NET framework 3.5 which allows you to define custom casts, but I'm using 2.0. In my RichClass definition I've created a constructor that allows me to pass in a RawClass object, then set all properties of the base to the corresponding properties of RawClass. It's messy. I was using encapsulation, and maybe should have stuck with that - but encapsulation's messy too. Who'd be a developer??

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”