473,378 Members | 1,162 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Casting between two classes derived from the same base class

Hi!

I've got a small challenge with my class library. I've got an abstract base
class with some protected fields. It has two derived classes, and it should
be possible to cast these classes to each other. The variables to be
persisted are the ones from the base class.

It is possible to cast upwards, but I'm not allowed to cast downwards. The
only solution I found was to create explicit casting operators on each of
the derived classes. The first step is to cast the source object to the base
class, and then create a new instance of the target class based on the
fields of the base class. But since the fields are protected, I can't read
them. The solution as of now is to change the protected fields to internal
fields. It works, but now all classes in the assembly can see the fields,
and I don't want that. :P

Anyone got a better solution?

Lars-Erik
Nov 16 '05 #1
2 9110
It is possible to cast upwards, but I'm not allowed to cast downwards.


that's correct. I think whenever you find yourself in a situation like
this, it's likely that your design is flawed.

but to do what you want, a copy constructor through inheritance will do the
trick

public class Base
{
protected int _i;

public Base()
{
}

public Base(Base clone)
{
this._i = clone._i;
}
}

public class Derived1 : Base
{
public void Set(int i)
{
this._i = i;
}
}

public class Derived2 : Base
{
public Derived2(Derived1 obj) : base(obj)
{
}

public int Get()
{
return this._i;
}
}

public class MyClass
{
public static void Main()
{
Derived1 obj1 = new Derived1();
obj1.Set( 100 );
Derived2 obj2 = new Derived2( obj1 );
Console.WriteLine( obj2.Get() );
}
}
Nov 16 '05 #2
On Wed, 10 Nov 2004 12:16:41 +0100, "Lars-Erik Aabech"
<la**************@markedspartner.noSPAMBLOCK> wrote:
It is possible to cast upwards, but I'm not allowed to cast downwards.


Downcasting is only allowed to the actual type or one of its parents.
It can't be any other way since a "sibling type" can have totally
different fields, so an actual data conversion is needed which can't
be automated. Casts along the inheritance hierarchy never change
data, they merely give you different views on the same data.

You can do a copy constructor like Daniel suggested, though the more
"standard" way to do this is to create a static "FromFoo" method:

public class Bar {
public static Bar FromFoo(Foo foo) {
Bar bar = new Bar(...);
bar.SomeBarData = SomeConverter(foo.SomeFooData);
return bar;
}
}

That's assuming that Foo and Bar are your two sibling classes. No
chance to access Foo's protected fields from Bar, though -- unless you
opt to use reflection, which is slow and convoluted.
--
http://www.kynosarges.de
Nov 16 '05 #3

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

Similar topics

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; }
0
by: Kurt Lange | last post by:
no... the array is created dynamically. and no... that defeats the purpose of what im trying todo.. encapsulate all initializing of variables in base class... derive from it... by deriving...
0
by: Lars-Erik Aabech | last post by:
Hi! I've got a small challenge with my class library. I've got an abstract base class with some protected fields. It has two derived classes, and it should be possible to cast these classes to...
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...
10
by: Brett Romero | last post by:
Say I have a class inheriting some base class: BaseClass { void Foo() { Update(); } }
24
by: AtariPete | last post by:
Hey All, I have a C# question for you regarding up casting (base to derived). I was wondering about the most elegant way (readable, less code) to cast from a base type to its derived type....
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...
19
by: jan.loucka | last post by:
Hi, We're building a mapping application and inside we're using open source dll called MapServer. This dll uses object model that has quite a few classes. In our app we however need to little bit...
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
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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...

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.