473,473 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Casting a C# base class object to a derived class type.

Is there any way to cast a base class object to a derived class datatype when
the derived class adds no new fields nor alters the object allocation in any
way?

The scenario would be where you want to extend a base class by adding only
methods and properties, however, only base class objects are provided to you.

Here is a sample:

public class Base
{
protected int val = 0;
}

public class Derived : Base
{
public int GetVal()
{
return val;
}
}

Then using those classes in a function like this:

public int Fn( Base a )
{
Derived b = (Derived)a;
return b.GetVal();
}

Assuming allocation doesn't change, there should be no harm in doing a cast
like this. Are there class modifiers that could handle this?

Thanks, Chris.
Nov 17 '05 #1
5 15183
Chris Capon wrote:
Is there any way to cast a base class object to a derived class datatype when
the derived class adds no new fields nor alters the object allocation in any
way?

The scenario would be where you want to extend a base class by adding only
methods and properties, however, only base class objects are provided to you.

Here is a sample:

public class Base
{
protected int val = 0;
}

public class Derived : Base
{
public int GetVal()
{
return val;
}
}

Then using those classes in a function like this:

public int Fn( Base a )
{
Derived b = (Derived)a;
return b.GetVal();
}
This would work fine unless a is not of type Derived, in which case you
would get an invalidcastexception.


Assuming allocation doesn't change, there should be no harm in doing a cast
like this. Are there class modifiers that could handle this?
What do you mean?
Thanks, Chris.


Have you tried this out?

JB
Nov 17 '05 #2
You can only cast it if a is actually an instance of Derived. You
should use the is keyword:

public int Fn( Base a )
{
if (a is Derived)
{
Derived b = (Derived)a;
return b.GetVal();
}
else
\\Do something else here;
}

Nov 17 '05 #3
Sorry. I may not have been clear in my original post. Perhaps the example
function should have been more like:

Base a = new Base();
Derived b = (Derived)a; //*** this will fail as an invalid cast
b.GetVal();

The above code casts an error because "a" has been created as a Base object,
not a Derived object. Attempting to cast "a" to the wrong type of object
causes an exception. But...

If the Derived class were to only add methods and properties, there should
be no harm in making this cast. For all intensive purposes, a Derived object
would look identical to a Base object in memory.

To give you a real world example, take the XmlElement object for instance.
It is created by calling XmlDocument.CreateElement(). Since an XmlElement
can't be created on its own, there is no way to extend this class with new
functionality. All you can do is wrapper a reference to it within another
class.

Suppose though, there were a class modifier which said, "this derived class
does not modify the base object so the two can be used interchangeably". You
could then extend base objects without knowing anything about how they were
created.

Cha', Chris.
Nov 17 '05 #4
Chris Capon <Ch********@discussions.microsoft.com> wrote:
Sorry. I may not have been clear in my original post. Perhaps the example
function should have been more like:

Base a = new Base();
Derived b = (Derived)a; //*** this will fail as an invalid cast
b.GetVal();

The above code casts an error because "a" has been created as a Base object,
not a Derived object. Attempting to cast "a" to the wrong type of object
causes an exception. But...

If the Derived class were to only add methods and properties, there should
be no harm in making this cast. For all intensive purposes, a Derived object
would look identical to a Base object in memory.
That doesn't mean it would be harmless though. It would behave
differently. If I pass you a reference to an instance of a base class,
I don't want you to be able to treat it as if it were an instance of a
derived class which might have radically different behaviour.
To give you a real world example, take the XmlElement object for instance.
It is created by calling XmlDocument.CreateElement(). Since an XmlElement
can't be created on its own, there is no way to extend this class with new
functionality. All you can do is wrapper a reference to it within another
class.
Yup.
Suppose though, there were a class modifier which said, "this derived class
does not modify the base object so the two can be used interchangeably". You
could then extend base objects without knowing anything about how they were
created.


Well, I'm afraid you can't. Personally I've rarely found I've wanted to
do this, but I'm glad I can't from a security point of view. Treating
an object as if it were an instance of a different type sounds pretty
dangerous to me.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #5


"Jon Skeet [C# MVP]" wrote:

Suppose though, there were a class modifier which said, "this derived class
does not modify the base object so the two can be used interchangeably". You
could then extend base objects without knowing anything about how they were
created.


Well, I'm afraid you can't. Personally I've rarely found I've wanted to
do this, but I'm glad I can't from a security point of view. Treating
an object as if it were an instance of a different type sounds pretty
dangerous to me.


Cool. Thanks anyway.

Nov 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Vinodh Kumar | last post by:
I see that casting changes the value of a pointer in case of multiple inheritance.In single inheritance also it is the same know?Isn't it? Vinodh Kumar P
3
by: Kurt | last post by:
i just can't figure out why something im doing is not working correctly.... public interface IInterface { int someProperty { get; set; }
7
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b;...
1
by: Mark McDonald | last post by:
This question kind of follows on from Mike Spass’ posting 10/11/2004; I don’t understand why you can’t declare an implicit operator to convert a base class to a derived class. The text...
44
by: Agoston Bejo | last post by:
What happens exactly when I do the following: struct A { int i; string j; A() {} }; void f(A& a) { cout << a.i << endl;
5
by: Larry Serflaten | last post by:
I am trying to build a chart to help me track what gets called when in the inheritance chain. I came across an error that has me puzzled. I have a derived class that inherits from a base class,...
23
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than...
11
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? ...
9
by: Jess | last post by:
Hello, It seems both static_cast and dynamic_cast can cast a base class pointer/reference to a derived class pointer/reference. If so, is there any difference between them? In addition, if I...
9
by: Taras_96 | last post by:
Hi everyone, I was experimenting with static_cast and reinterpret cast #include <iostream> struct A1 { int a; }; struct A2 { double d; }; struct B : public A1, A2
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.