Question

Inheritence - Create derived class from base class...options???

Asked by: pbfonline

Assume I have Class Animal.  And Class Monkey, which is Derived from Animal.  

If I have a Class Animal, is there any way to "convert" it to Monkey without copying over all of the properties?

Animal is the Base Class of Monkey, so I'm hoping there's a way to convert (or actually "redim preserve") the base object and just add in the additional properties, methods, etc to make it a Monkey, but I can't figure it out.

Can you Redim Preserve myAnimal as Monkey?
Can you pass Animal into the Constructor of Monkey and use it as the base class?

Animal is already instantiated.  I just want to use it as the base class for a New Monkey.

Can you do this in VB.Net?  

Public Class Animal
    Public Name as string 
    Public Legs as Int16
End Class
 
Public Class Monkey
    Inherits Animal
    Public HasTail as Boolean
End Class
 
----------------- Test Code ------------------
Dim myPet as New Animal
myPet.Legs = 2
myPet.Name = "Sparky"
 
Redim Preserve myPet Monkey
Debug.Print(myPet.HasTail)
 
'Can this be done?  

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-05 at 05:48:43ID24874327
Tags

Inheritence

,

Polymorphism

,

.Net

,

OOP

,

Object

,

Oriented

,

Redim

,

Preserve

Topics

Software/Systems Design

,

Miscellaneous Programming

,

.NET

Participating Experts
5
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Copy constructor and = operators for MFC derived classes
    We have classes derived from MFC classes and/or MFC class is one of the mebers of the class. e.g. CListBox is a member of one of our class. Customer has asked us to provide copy constructor and assignment for all the classes. What I want to know is - -Is there default copy ...
  2. Constructor Firing Order For Derived Classes
    Class Parent Class Child Derives from Parent When I init an object of class Child, it fires the Parent's default constructor FIRST, then proceeds with it's own. Is there a way I can explicitly choose when to have the parent's constructor fire? ie. Child() { //do some wo...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: RolandDeschainPosted on 2009-11-05 at 06:05:33ID: 25749519

Mmmm... I don't think this can be done. Probably you must do this:

Public Class Monkey
    Inherits Animal

    Public Sub New()
        'This empty constructor allows you to instance new blank objects of Monkey class
    End Sub

    Public Sub New(ByVal Parent As Animal)
        'This constructor allows you to create a new Monkey object based on an Animal object,
        'by copying its properties
        With Me
            .Name = Parent.Name
            .Legs = Parent.Legs
            '... and so on
        End With
    End Sub
End Class

'Later, on your code:
Dim myAnimal As New Animal
'.... set animal properties

Dim myMonkey As New Monkey(myAnimal)

I think this is the right approach.

Hope that helps.

 

by: pbfonlinePosted on 2009-11-05 at 06:35:12ID: 25749826

Thanks for the attempt, but this is not what I am looking for.  From my original post:  

"If I have a Class Animal, is there any way to "convert" it to Monkey without copying over all of the properties?"

Copying over the individual properties can get very cumbersome, and will cause me to go back into the derived classes and update them all individually each time a property is added to the base class.  

Because the base class is part of the derived class, I was hoping there was a way to tell .Net to create the derived class, using the base class (and keep the existing data).

 

by: andycroftsPosted on 2009-11-05 at 06:52:23ID: 25750027

Have yout tried something like

myMonkey = CType(myAnimal, Monkey)

or

myMonkey = DirectCast(myAnimal, Monkey)

 

by: andycroftsPosted on 2009-11-05 at 06:53:33ID: 25750046

myPet = CType(myPet , Monkey)

or

myPet = DirectCast(myPet , Monkey)

 

by: andycroftsPosted on 2009-11-05 at 06:54:21ID: 25750057

I guess that is not it either

 

by: TribmosPosted on 2009-11-05 at 07:49:12ID: 25750722

The problem with this is that all Monkeys are Animals, but not all Animals are Monkeys.  You can type cast any higher order as their lower order (or back up) since the object is all those types.  This structure helps enforce rules which keeps the heirachy stable.  The only way to do what your proposing is to have Monkey be able to take in an animal object and it copy over base items that can be copied.

Forgive the code as i'm a tad rusty on the exact VB syntax.
This is similar to RolandDeschain's example, however to ensure that all children get the properties, you only need to update the copy routine in the Animal class

Public Class Animal
    Public Name as string 
    Public Legs as Int16
  Public Sub CopyItem(source as Animal)
    Me.Name = source.Name
    Me.Legs = source.Legs
  End Sub
End Class
 
Public Class Monkey
    Inherits Animal
    Public HasTail as Boolean
  Public Sub New(source as Animal)
    CopyItem(source)
  End Sub
  Public Sub New()
  End Sub
End Class
---------
Dim myPet as New Animal
myPet.Legs = 2
myPet.Name = "Sparky"
 
Dim myPet as new Monkey(myPet)
Debug.Print(myPet.HasTail)
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:

Select allOpen in new window

 

by: Idle_MindPosted on 2009-11-05 at 08:11:28ID: 25750950

I think Roland was on the right track...all you need to do is add a little REFLECTION magic and it will be completely generic and not need to be updated as you add/remove fields:

Public Class Form1
 
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim myPet As New Animal
        myPet.Legs = 2
        myPet.Name = "Sparky"
 
        Dim myMonkey As New Monkey(myPet)
        myMonkey.HasTail = True
        Debug.Print("myMonkey.Legs = " & myMonkey.Legs)
        Debug.Print("myMonkey.Name = " & myMonkey.Name)
        Debug.Print("myMonkey.HasTail = " & myMonkey.HasTail)
    End Sub
 
End Class
 
Public Class Animal
 
    Public Name As String
    Public Legs As Int16
 
End Class
 
Public Class Monkey
    Inherits Animal
 
    Public Sub New()
    End Sub
 
    Public Sub New(ByVal DeriveFrom As Animal)
        For Each fi As System.Reflection.FieldInfo In DeriveFrom.GetType.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
            Dim fi2 As System.Reflection.FieldInfo = Me.GetType.GetField(fi.Name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
            If Not IsNothing(fi2) Then
                fi2.SetValue(Me, fi.GetValue(DeriveFrom))
            End If
        Next
    End Sub
 
    Public HasTail As Boolean
 
End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:

Select allOpen in new window

 

by: pbfonlinePosted on 2009-11-05 at 08:31:34ID: 25751150

I know that not all Animals are Monkeys...  But all Monkeys have the base properties and functions of Animals, so I don't want to have to create a whole new Monkey...  And I don't want to have to care about what additional properties a monkey has, because all I want to do is get a new Monkey that uses my initiated Animal as it's base - but without copying properties (at least not individually)...

The best way I have come up with so far is to use serialization to serialize Animal, change it's serialized type to Monkey, then deserialize it.  The attached code file does this.

It does have a problem, as it will obviously have overhead in the conversion process - but I don't need to know anything about either object to do this - as long as they are "serializable".  

So, I can convert a base object into any object that it derives to with a simple function call.
 - If the base object changes, all new properties and fields get copied automatically (as defined by the serialization of the object).

So, the only outstanding question I have...

Can you achieve this without serialization/deserailization?

    Public Class Convert
        Public Shared Function ToDerivedType(Of pDerivedType)(ByRef pBase As Object) As pDerivedType
            Dim myWriter As New IO.StringWriter
            Dim oXSBase As XmlSerializer = New XmlSerializer(pBase.GetType())
            oXSBase.Serialize(myWriter, pBase)
 
            Dim myNewData As String = myWriter.ToString()
            myNewData = Replace(myNewData, "<" & pBase.GetType().Name & " xmlns", "<" & GetType(pDerivedType).Name & " xmlns")
            myNewData = Replace(myNewData, "</" & pBase.GetType().Name & ">", "</" & GetType(pDerivedType).Name & ">")
 
            Dim myReader As New IO.StringReader(myNewData)
            Dim oXSDerived As XmlSerializer = New XmlSerializer(GetType(pDerivedType))
            Return oXSDerived.Deserialize(myReader)
        End Function
    End Class
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: pbfonlinePosted on 2009-11-05 at 08:33:54ID: 25751171

PS.  Test code to do this is:

    <Serializable()> _
    Public Class Animal
        Public Name As String
        Public Legs As Int16
        Public Overrides Function ToString() As String
            Return Name & " has " & Legs & " legs"
        End Function
    End Class
 
    <Serializable()> _
    Public Class Monkey
        Inherits Animal
        Public ReadOnly Property HasTail() As Boolean
            Get
                Return True
            End Get
        End Property
        Public Overrides Function ToString() As String
            Return MyBase.ToString() & IIf(HasTail, " and a", " but no") & " tail!"
        End Function
    End Class
 
 
Public Sub Test()
    Dim myAnimal As New Simple.Animal
    myAnimal.Name = "Bingo"
    myAnimal.Legs = 2
    MessageBox.Show(myAnimal.ToString())
 
    Dim myMonkey As Simple.Monkey = Simple.Convert.ToDerivedType(Of Simple.Monkey)(myAnimal)
    MessageBox.Show(myMonkey.ToString())
End Sub

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

Select allOpen in new window

 

by: Idle_MindPosted on 2009-11-05 at 08:37:44ID: 25751223

"...all I want to do is get a new Monkey that uses my initiated Animal as it's base - but without copying properties (at least not individually)..."

Did you not see my post?...it copies everyhing via Reflection.  It will work even when you change the base class fields...

 

by: pbfonlinePosted on 2009-11-05 at 08:38:31ID: 25751231

And sorry, but yes - I tried all of the following:

dim myMonkey as Monkey = myAnimal
dim myMonkey as Monkey = CType(myAnimal, Monkey)
dim myMonkey as Monkey = DirectCast(myAnimal, Monkey)

I've even tried to add a New Constructor in Monkey that accepts an object of type Animal and set MyBase = pAnimal, but it's not allowed.  This would be the best solution, as that is EXACTLY what I want to do.  Create a monkey and pass the base object into the New Constructor to override MyBase...

It just does not seem to be possible.

 

by: pbfonlinePosted on 2009-11-05 at 08:42:28ID: 25751281

Idle_Mind

Your solution would work in a simple example, but I'm trying to avoid copying the properties.  I know that using reflection is possible, but I have read that it cannot always be done in complex objects (as the real world will have).  

Regardless of your solution or mine, which both work - I'm trying to do it without copying anything.  The base object exists.  I should be able to create a New derived object from it - but I can't figure it out.

 

by: Idle_MindPosted on 2009-11-05 at 08:42:47ID: 25751289

I think you've looked at the wrong comments...  =\

My proposed solution is here:
http://www.experts-exchange.com/Programming/Theory/Software-Design/Q_24874327.html#25750950

Look closely!...it's using REFLECTION...not any type of casting.

 

by: Idle_MindPosted on 2009-11-05 at 08:48:45ID: 25751364

(we're cross-posting)

Not sure there is a "one liner" solution to your problem.

I've posted a previous solution here that is similar to yours:
http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_21164630.html

 

by: pbfonlinePosted on 2009-11-05 at 09:07:36ID: 25751598

I think you're right Idle_Mind...  

If I understand it right, I can use the Binary Formatter instead of the XmlSerialization, and it will keep the object in binary form - and thus speed up the "conversion process"...  

Then, essentially, I'll be doing exactly what I want - which is creating a new monkey with existing animal, without re-initializing animal, right?

 

by: Idle_MindPosted on 2009-11-05 at 09:10:51ID: 25751628

It should work...though I don't really know if it's any faster.  You'll have to test it... ;)

 

by: b_levittPosted on 2009-11-05 at 09:13:04ID: 25751653

Upcasting (or downcasting - not sure if I have them flipped) is not possible.  

I guess at this point the only question to ask is 'why'.   Why do you need to do this?  In the case of most base classes like this, Animal should conceptually be abstract.  There is no such animal as 'animal' so consequently constructing such a type shouldn't be allowed.  

Why can't  you use reflection?  

Why can't you use a factory pattern to create the correct type and cast it down to animal?

Why can't you use serialization?

And I've been here before so I understand what it's like to be on the other end of this question, but why are you so hell-bent on making the compiler do something for you that you already have a handful of ways to do yourself?

 

by: pbfonlinePosted on 2009-11-05 at 09:38:32ID: 25751885

b_levitt

I'm trying to encapsulate logic, functionality, etc inside of an object that is NOT exposed outside of my business layer.  I want the business layer to just "see" an animal.  It doesn't need to know what kind of animal it is - it just needs to know it's an animal.

However, when that animal object is back to the business layer, it actually IS A monkey, and the business layer knows this - and therefore uses the hidden functionality allowed in the business layer because the BL can tell it's not just an animal, but a monkey.

This keeps the presentation of the object outside the business layer very simple, but also allows the business layer to have full access.

So, I want the presentation layer to be able to pass the business layer an Animal (by reference).  When the BL sees the object is an animal, it will convert it to a monkey and set the reference to point to the monkey instead.  But, the PL doesn't know the difference because it's still inhereted from Animal.

The BL has full access to everything that it needs.
The PL doesn't even know the difference.

I'm trying to enforce separation of logic and complexity in the layers so that one layer doesn't even see what it doesn't need to know.

 

by: pbfonlinePosted on 2009-11-05 at 09:39:26ID: 25751894

In paragraph 1 above, I mean:

"I want the presentation layer to just "see" an animal.  It doesn't need to know what kind of animal it is - it just needs to know it's an animal."

 

by: Idle_MindPosted on 2009-11-05 at 09:41:45ID: 25751911

You could consider implementing an Animal INTERFACE instead of deriving from a Base Class.  Then the PL just gets pass something the implements the Interface and can perform the "base operations" on that object regardless of what it actually is.

 

by: TribmosPosted on 2009-11-05 at 10:26:49ID: 25752346

Not to derail, but I know in C# you can refer to everything as the base type "object" and if you perform an "IS" comparison you can determine what class it really is (or part of).

Therefore you could have arrays of Animals, and refer to them as such, but if you could also go through and find which ones are monkeys.   Does VB not have that same capability?

example being
Dim X as Animal
X = new Monkey()

Though because X is referred to as Animal only those parameters are visible.
however if you have a function that accepts Monkeys this one would be a valid item.
Or does that not work in VB?

 

by: pbfonlinePosted on 2009-11-05 at 11:45:50ID: 31650480

The "solution" was never found for what I want to do - but several alternatives were discussed.

 

by: pbfonlinePosted on 2009-11-06 at 13:01:09ID: 25763013

Tribmos, that actually looks like what I'm trying to do...  

Dim X as Animal
X.Name = "Bingo"
X = new Monkey()

But in VB, when you say X = new Monkey, it will create a New instance of Monkey from scratch and it will have no instantiated properties of the previously instantiated Animal...  

What I'd like to do is keep X.Name populated and use X to create an instance of Monkey.  

 

by: pbfonlinePosted on 2009-11-06 at 13:47:10ID: 25763363

Idle

BTW - I wrote the Class Converter utility using reflection (as you suggested) and it is much faster than doing it my way (converting using serialization).  

However, I did run across a problem.  The copy using reflection logic does not work on private member variables of the base type.  It finds them on the base type when it's looping through, but can't see them on the derived type (because they're private on the base, and not exposed in the derived object).

 

by: pbfonlinePosted on 2009-11-06 at 14:30:49ID: 25763648

PS.  I just fixed the problem.  The private variables are able to be copied to the object, but you have to climb up the base tree until you find it...

        Public Shared Sub CopyDataUsingReflection(ByRef pBase As Object, ByVal pDerived As Object)
            For Each fi As System.Reflection.FieldInfo In pBase.GetType.GetFields(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
                Dim fi2 As System.Reflection.FieldInfo
                Dim curType As Type = pDerived.GetType()
                Do
                    fi2 = curType.GetField(fi.Name, Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public Or Reflection.BindingFlags.NonPublic)
                    If Not IsNothing(fi2) Then
                        fi2.SetValue(pDerived, fi.GetValue(pBase))
                        Exit Do
                    End If
                    If curType.BaseType() Is GetType(System.Object) OrElse curType.BaseType() Is Nothing Then Exit Do Else curType = curType.BaseType()
                Loop Until curType Is Nothing
            Next
        End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...