472,958 Members | 1,983 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Cast from parent(base) to son(derived) class?

I have a simple class:

public class BaseClass
{
private string propertyA;

protected string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}

private string propertyB;

protected string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

Now I have a derived class:

public class DerivedClass
{
private string propertyC;

protected string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
}

How can I create a constructor method of DerivedClass that receives an
object from the base class and casts it to derived class (so as to copy
the value of the properties they have in common)?

I ask this because this constructor obviously raises a compile error:

public DerivedClass(BaseClass oObj)
{
this = (DerivedClass)oObj;
}

Is there a method to do this apart from Reflection?

Thanks in advance.

Andrés [ knocte ]

--
Dec 19 '06 #1
11 3214

Andrés G. Aragoneses [ knocte ] wrote:
I have a simple class:

public class BaseClass
{
private string propertyA;

protected string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}

private string propertyB;

protected string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

Now I have a derived class:

public class DerivedClass
{
private string propertyC;

protected string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
}

How can I create a constructor method of DerivedClass that receives an
object from the base class and casts it to derived class (so as to copy
the value of the properties they have in common)?
If you only need to copy the properties they have in common, you don't
need to cast it.

Just use:

PropertyA = oObj.PropertyA;
PropertyB = oObj.PropertyB;

Jon

Dec 19 '06 #2
Jon Skeet [C# MVP] escribió:
If you only need to copy the properties they have in common, you don't
need to cast it.

Just use:

PropertyA = oObj.PropertyA;
PropertyB = oObj.PropertyB;
Yes, but I want to avoid coding that, because it should be automatic (as
DerivedClass derives from BaseClass and thus it contains the same
properties).

Thanks.

Andrés [ knocte ]

--
Dec 19 '06 #3
Hello Andres,

The following code works for me...

class Parent
{
private int _A;

public int A
{
get { return _A; }
set { _A = value; }
}

private int _B;

public int B
{
get { return _B; }
set { _B = value; }
}
}

class Child : Parent
{
public Child(Parent p)
{
this.A = p.A;
this.B = p.B;
}

private int _C;

public int C
{
get { return _C; }
set { _C = value; }
}

}

private void button1_Click(object sender, EventArgs e)
{
Parent p = new Parent();
p.A = 1;
p.B = 2;

Child c = new Child(p);
c.C = 3;

MessageBox.Show(c.A.ToString());
}

--
Cheers,
Gary
http://www.garyshort.org/
Andrés G. Aragoneses [ knocte ] wrote:
I have a simple class:

public class BaseClass
{
private string propertyA;

protected string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}

private string propertyB;

protected string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

Now I have a derived class:

public class DerivedClass
{
private string propertyC;

protected string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
}

How can I create a constructor method of DerivedClass that receives an
object from the base class and casts it to derived class (so as to copy
the value of the properties they have in common)?

I ask this because this constructor obviously raises a compile error:

public DerivedClass(BaseClass oObj)
{
this = (DerivedClass)oObj;
}

Is there a method to do this apart from Reflection?

Thanks in advance.

Andrés [ knocte ]

--
Dec 19 '06 #4
ga**@garyshort.org escribió:
Hello Andres,

The following code works for me...

class Parent
{
private int _A;

public int A
{
get { return _A; }
set { _A = value; }
}

private int _B;

public int B
{
get { return _B; }
set { _B = value; }
}
}

class Child : Parent
{
public Child(Parent p)
{
this.A = p.A;
this.B = p.B;
}

private int _C;

public int C
{
get { return _C; }
set { _C = value; }
}

}

private void button1_Click(object sender, EventArgs e)
{
Parent p = new Parent();
p.A = 1;
p.B = 2;

Child c = new Child(p);
c.C = 3;

MessageBox.Show(c.A.ToString());
}
Thanks, but what I want to do is avoid coding the copy of the
properties. I wondered if it was a way of doing that *without*
reflection. I guess there isn't any.

Regards,

Andrés [ knocte ]

--
Dec 19 '06 #5
Well, extracting just the "base" part of a derived-class instance
isn't really what it is designed to do... if you need this behaviour,
berhaps a different design? Encapsulation - i.e. the "child" contains
the "parent", perhaps using an interface to expose the parent's
properties as a facade (so you can treat the "child" as an "IParent").
This allows you to simply obtain the encapsulated object directly
(assuming it is exposed as a property).

Not OO in inheritance terms, but then again inheritance isn't the
answer to every problem...

Marc
Dec 19 '06 #6
Andrés G. Aragoneses [ knocte ] wrote:
Jon Skeet [C# MVP] escribió:
If you only need to copy the properties they have in common, you don't
need to cast it.

Just use:

PropertyA = oObj.PropertyA;
PropertyB = oObj.PropertyB;

Yes, but I want to avoid coding that, because it should be automatic (as
DerivedClass derives from BaseClass and thus it contains the same
properties).
You'll need to code it *somewhere* unless you use reflection - you may
want to put it a base class constructor though.

Jon

Dec 19 '06 #7
Example using your names... note that "baseclass" and "derivedclass"
are a little vaguewhen removed from inhetance, but I thought it would
be clearer to keep the same for reference purposes. Note also that the
base (either BaseClass or IBaseClass) could be made cloneable
(ICloneable) if you needed to make copies of just the base section.

Marc

using System;
class Program
{
static void Main()
{
DerivedClass dc = new DerivedClass();
dc.PropertyA = "A";
dc.PropertyB = "B";
dc.PropertyC = "C";
IBaseClass bc = dc.BaseClass;
}
}
public interface IBaseClass
{
string PropertyA { get;set;}
string PropertyB {get;set;}
}
public class BaseClass : IBaseClass
{
private string propertyA;
public string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}
private string propertyB;
public string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

public class DerivedClass : IBaseClass
{
public IBaseClass BaseClass { get { return baseClass; } }
private readonly IBaseClass baseClass;
public DerivedClass() : this(new BaseClass()) { }
public DerivedClass(IBaseClass baseClass)
{
if (baseClass == null) throw new ArgumentNullException();
this.baseClass = baseClass;
}
private string propertyC;
public string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
public string PropertyA
{
get { return baseClass.PropertyA; }
set { baseClass.PropertyA = value; }
}
public string PropertyB
{
get { return baseClass.PropertyB; }
set { baseClass.PropertyB = value; }
}
}

Dec 19 '06 #8
Marc Gravell escribió:
Example using your names... note that "baseclass" and "derivedclass"
are a little vaguewhen removed from inhetance, but I thought it would
be clearer to keep the same for reference purposes. Note also that the
base (either BaseClass or IBaseClass) could be made cloneable
(ICloneable) if you needed to make copies of just the base section.

Marc

using System;
class Program
{
static void Main()
{
DerivedClass dc = new DerivedClass();
dc.PropertyA = "A";
dc.PropertyB = "B";
dc.PropertyC = "C";
IBaseClass bc = dc.BaseClass;
}
}
public interface IBaseClass
{
string PropertyA { get;set;}
string PropertyB {get;set;}
}
public class BaseClass : IBaseClass
{
private string propertyA;
public string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}
private string propertyB;
public string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

public class DerivedClass : IBaseClass
{
public IBaseClass BaseClass { get { return baseClass; } }
private readonly IBaseClass baseClass;
public DerivedClass() : this(new BaseClass()) { }
public DerivedClass(IBaseClass baseClass)
{
if (baseClass == null) throw new ArgumentNullException();
this.baseClass = baseClass;
}
private string propertyC;
public string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
public string PropertyA
{
get { return baseClass.PropertyA; }
set { baseClass.PropertyA = value; }
}
public string PropertyB
{
get { return baseClass.PropertyB; }
set { baseClass.PropertyB = value; }
}
}


Thanks for the example, but I think it's not valid as an answer for the
initial question, because:

1) You're obtaining a BaseClass object from the DerivedClass, which is
the opposite what I wanted (I want to create a DerivedClass object from
the BaseClass object).

2) You have avoided the "cloning/copying code" but you have had to
implement the properties of the IBaseClass in DerivedClass, so then
you're writing more code that wouldn't have been necessary because those
properties were already in the BaseClass (all I want to do is avoid much
writing so as to be productive ;), I think I will end with a reflection
solution, or a new wishlist item for a future version of C# :) )

Thanks.

Andrés [ knocte ]
--
Dec 19 '06 #9
Hi Andrés,
I think I will end with a reflection solution, or a new wishlist item for
a future version of C# :) )
I say go with the wishlist (but don't count on it :)

--
Dave Sexton

""Andrés G. Aragoneses [ knocte ]"" <kn****@NO-SPAM-PLEASE-gmail.comwrote
in message news:e3**************@TK2MSFTNGP04.phx.gbl...
Marc Gravell escribió:
>Example using your names... note that "baseclass" and "derivedclass"
are a little vaguewhen removed from inhetance, but I thought it would
be clearer to keep the same for reference purposes. Note also that the
base (either BaseClass or IBaseClass) could be made cloneable
(ICloneable) if you needed to make copies of just the base section.

Marc

using System;
class Program
{
static void Main()
{
DerivedClass dc = new DerivedClass();
dc.PropertyA = "A";
dc.PropertyB = "B";
dc.PropertyC = "C";
IBaseClass bc = dc.BaseClass;
}
}
public interface IBaseClass
{
string PropertyA { get;set;}
string PropertyB {get;set;}
}
public class BaseClass : IBaseClass
{
private string propertyA;
public string PropertyA
{
get { return propertyA; }
set { propertyA = value; }
}
private string propertyB;
public string PropertyB
{
get { return propertyB; }
set { propertyB = value; }
}
}

public class DerivedClass : IBaseClass
{
public IBaseClass BaseClass { get { return baseClass; } }
private readonly IBaseClass baseClass;
public DerivedClass() : this(new BaseClass()) { }
public DerivedClass(IBaseClass baseClass)
{
if (baseClass == null) throw new ArgumentNullException();
this.baseClass = baseClass;
}
private string propertyC;
public string PropertyC
{
get { return propertyC; }
set { propertyC = value; }
}
public string PropertyA
{
get { return baseClass.PropertyA; }
set { baseClass.PropertyA = value; }
}
public string PropertyB
{
get { return baseClass.PropertyB; }
set { baseClass.PropertyB = value; }
}
}

Thanks for the example, but I think it's not valid as an answer for the
initial question, because:

1) You're obtaining a BaseClass object from the DerivedClass, which is the
opposite what I wanted (I want to create a DerivedClass object from the
BaseClass object).

2) You have avoided the "cloning/copying code" but you have had to
implement the properties of the IBaseClass in DerivedClass, so then you're
writing more code that wouldn't have been necessary because those
properties were already in the BaseClass (all I want to do is avoid much
writing so as to be productive ;), I think I will end with a reflection
solution, or a new wishlist item for a future version of C# :) )

Thanks.

Andrés [ knocte ]
--

Dec 19 '06 #10
Hi,
Yes, but I want to avoid coding that, because it should be automatic (as
DerivedClass derives from BaseClass and thus it contains the same
properties).
I think you have a little confusion, it's true that the derived class
contain the parent properties. but what you are doing is a "cloning"
operation. You have one instance of Parent and you want to create another
instance (it does not matter if it's a Parent or Derived) you still need to
copy the values from the first instance to the new instance.
--
Ignacio Machin
machin AT laceupsolutions com
Dec 19 '06 #11
Ignacio Machin ( .NET/ C# MVP ) escribió:
Hi,
>Yes, but I want to avoid coding that, because it should be automatic (as
DerivedClass derives from BaseClass and thus it contains the same
properties).

I think you have a little confusion, it's true that the derived class
contain the parent properties. but what you are doing is a "cloning"
operation. You have one instance of Parent and you want to create another
instance (it does not matter if it's a Parent or Derived) you still need to
copy the values from the first instance to the new instance.
Mmmmm, I think you're right. I think I got confused thinking that I
could change the type of the object at runtime, so as to transform it
into the derived class (adding the new properties and avoiding the N
cloning operations). But now I see that this would be a new concept that
the runtime should support (not only the language), I think...

Regards,

Andrés [ knocte ]

--

Dec 19 '06 #12

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

Similar topics

3
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? ...
1
by: ypjofficial | last post by:
Dear All, According to OOPs , a base class pointer can to point to derived class object....call this as fact1 But somehow I am not comfortable while understanding this concept. The explanaition...
10
by: Bhan | last post by:
Using Ptr of derived class to point to base class and viceversa class base { .... } class derived : public base { .... }
2
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...
6
by: Taran | last post by:
Hi All, I tried something with the C++ I know and some things just seem strange. consider: #include <iostream> using namespace std;
11
by: Darren.Ratcliffe | last post by:
Hi guys Posted what was probably a rather confusing post about this the other day, so I am going to have another go and see if I can make more sense. This sis purely a I've got a base class...
14
by: Jo | last post by:
Hi, Is there a generic way to access the (virtual) functions in the base class of a class? Like in: if (!this->Foo(something)) return(((Base*)this)->Foo(something)); // for a normal member...
4
by: Javier | last post by:
Hello, is this possible? I have a pure virtual function in the base class (to force the programmers of the derived classes to have this function implemented) but I want to call the derived class...
13
by: Rahul | last post by:
Hi Everyone, I was just playing around virtual functions and landed up with the following, class Base1 { public: virtual void sample() { printf("base::sample\n");
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.