tags:

views:

137

answers:

5

Writing an asp.net mvc app and i have something like this...

Public Class AA
'... has some variables...
End Class

Public Class BB
Inherits AA
Public ExtraVariable As Integer ' just adds another variable and thats it!
End Class

So, now in my program, i just want to copy object of type AA to an empty variable of type BB?

it makes sense to do this, as i expect all the fields in AA type object to be copied to the newly created BB type object, and the ExtraVariable in the BB type object i would (will) just assign a value to it later (after the copy) on my own time!!

I know copying BB type to AA type would not be appropriate as there would be lost data!

But im trying to copy AA to BB, I've used both DirectCast and CType to do this, and i keep getting "unable to cast" error!!!

Note: I'm using vb.net (but can read c#, no problems)

+4  A: 

It seems like you're confusing copying with simple assignment.

What you likely want to do is define a constructor on BB that takes an AA as an argument, and copies the values.

Anon.
anon, thanks for your reply, just to clarify, are you suggesting that i copy all of the members in AA to BB in the constructor?like, as in field by field, so if i have 5 vars in AA, then assign those 5 vars line by line basically?
Erx_VB.NExT.Coder
Yes, you'll likely have to write a line of code for each member at some point. However, note that you can call any of the base class constructors, which could end up doing a lot of the work for you.
Anon.
Erx_VB.NExT.Coder
+1  A: 

I do not think what you are trying is possible. A reference to a derived class must actually refer to an instance of the derived class

see: Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

Here is one way to get the values

        public class AA
        {
            public string name;
        }
        public class BB : AA 
        {
            public BB(AA aa)
            {
                name = aa.name;
            }
        }
Asad Butt
really? so it's not possible then? you have to do it field by field?
Erx_VB.NExT.Coder
ok, i was fearing this. i suppose instead of inheriting, i'll just have to have class BB only, and public class AA as a variable in class BB! this sound kosher?
Erx_VB.NExT.Coder
It is probably the Design of your module that needs attention
Asad Butt
that should depend on the relationship between AA and BB. if BB 'is a' AA then it should be inheritance. If BB 'has a' AA then it should be composition as you indicate above. Having said that composition is often a better approach. Obviously if you want the properties of AA to be visible through BB then you will have to create properties in BB which delegate to AA if you don't inherit. Sounds like you are trying to save a bit of typing to me, which is not the best design strategy :)
Sam Holder
oh AA is actually a "Comment" like comments on websites that ppl write, it's created from a db type... so there are several variables (like extra variables) that type Comment (BB) needs to have, but shouldn't have stored in a database... so just adding non db fields to the Comment type... this is what im doing, is there something wrong with my / that design?
Erx_VB.NExT.Coder
oh now, i dont mind typing, i just want to make sure im doign things the way it should be done, AA actually has a lot of variables, but assuming it has about 100 variables, doesn't sound right to copy item by item
Erx_VB.NExT.Coder
why do you need a new class for the non db stuff. Why can't you just add the extra properties to AA? Is there a reason it can only contain db stuff?
Sam Holder
@Sam: am, because AA is in a dbml file that visual studio creates by looking at the database design (creates appropriate classes from it) so we can use db items in true OOP style... its generally best not to touch the auto-generated classes, i know i can use partial classing as well, but still not good as i dont need the class to be extended Always, only _sometimes_, so thats why its either inheritance, or creating a public variable of AA inside BB, what do you think? thanks mate.
Erx_VB.NExT.Coder
I'd go for composition in that case, and I'd think about using the decorator pattern http://en.wikipedia.org/wiki/Decorator_pattern
Sam Holder
A: 

It seems that you misunderstood the inheritance concept correctly.

When you copy BB to AA you don't miss any data, as you can get the data if you cast it again to BB.

AA cannot be cast to BB directly, because AA is not BB. If you want, you can do a custom cast and you can specify how the cast will be.

But, doing this it not will be very intuitive, and is better to put the value "by hand":

bb.Value1 = aa.Value1
bb.Value2 = aa.Value2
bb.Value3 = aa.Value3

Nothing wrong about it.

Mendy
copying (not by reference, but by value) in one shot, BB to AA would mean lost data (ExtraVariable would be lost), as in AA will not carry it since it's not allocated. correct me if im missing something? also, the second part of my response, are you sayign i have to pretty much copy each variable one by one?
Erx_VB.NExT.Coder
@Erx_VB.NExT.Coder: You missing a lot. If after I put BB in AA, I put again AA to BB, the data is come back. so this mean you don't miss any thing, you just need to cast it to the specific type you wanna work with.
Mendy
but i am refering to COPYING BY VALUE not Copying BY REFERENCE, in the example i just gave you. what you suggest would be impossible. but i understand if it is by REFERENCE then what you said is correct.
Erx_VB.NExT.Coder
If you mean by 'copy' is to assign the veritable, like AA = BB, this is by reference.
Mendy
+1  A: 

As anon says you probably want to pass AA into BB's constructor, where you can copy all the elements:

public class AA
{
//some variables
}

public class BB : AA
{
    public BB(AA aa)
    {
    //Set BBs variables to those in AA
    someVariable= aa.someVariable
    }

    public int SomeExtraProperty{get;set;}
}

but obviously you'll have any inherited constructors available to you which you could reuse if appropriate.

EDIT

based on some of the comments above, you could also do:

public class BB : AA
{
    private AA _aa;
    public BB(AA aa)
    {
    //Set BBs variables to those in AA
    _aa=aa;
    }

    public int SomeExtraProperty{get;set;}

    //override inherted members and just delegate to the internal object
    public override int SomeMethod()
    {
       return _aa.SomeMethod();
    }
}

or maybe go for the Decorator Pattern

Sam Holder
thanks mate that clarifies it even further.
Erx_VB.NExT.Coder
A: 

There are some good posts on object cloning you may want to have a look at, for example http://stackoverflow.com/questions/78536/cloning-objects-in-c/78612#78612, but what people have already mentioned here about manually copying is probably your best bet in copying from one Type to another.

Your problem seems to in your understanding of inheritance and casting. Something to bare in mind when casting is that you can easily cast down to a simpler type, but vice versa is a lot trickier, and not possible with a simple cast

ie

with the classes:

public class BaseObject 
{

}

public class InheritedObject : BaseObject
{

}

public class BaseObjectConsumer()
{
    Consumer(BaseObject base);
}

public class InheritedObjectConsumer()
{

}

The following should be considered:

InheritedObject io = new InheritedObject();
BaseObject bo = new BaseObject();

BaseObjectConsumer(io); //this is possible as the InheritedObject is being 'viewed' as a BaseObject

InheritedObjectConsumer(bo); //Not as simple, as the Base object is not necessarily an Inherited object, so we can't cast 'up'
johnc