Reputation: 277
I have 2 objects, Object A and Object B. A has the properties color and size and B has the the properties color, size and depth.
Both A and B inherits from C which is an abstract class.
How can I convert B to A at run-time?
abstract class C {
}
Class A: C {
int color;
int size;
}
Class B: C {
int color;
int size;
int depth;
}
main() {
//creating object A
A objA = new A();
A.color = 46;
A.size = 90;
//creating object B
B objB = new B();
B.color = 23;
B.size = 10;
B.depth = 78;
//How to do casting
A = B;
}
Upvotes: 2
Views: 10972
Reputation: 32954
You can't directly convert B to A in this case without some extra work.
if you move the common fields into the base class then you can pass a B into a method that expects an instance of the base class and it will just access the common fields.
Your other options if you don't want to do that are to write a conversion method or add an implicit conversion so you can cast B to A or to use a library like Automapper as had been suggested
implicit conversion could look something like this
Public static implicit operator A (B theB)
{
return new A (theB.colour, theB.size);
}
And would then allow you to cast your B instance to an A instance.
A myA = (A)myB;
I would still question if this is a good idea
Upvotes: 1
Reputation: 9166
You can add an explicit cast operator to the in class B
:
Class B: C {
int color;
int size;
int depth;
public static explicit operator A(B b)
{
return new A() {color = b.color, size = b.size};
}
}
You can then convert a B
to an A
using a cast:
A a = (A)b;
Upvotes: 10
Reputation: 22770
When I've had problems like this I've used AutoMapper.
This is a free library that will allow you to map one object to another and even allow you to map one field to another of a different name and type.
You can also convert a List<A>
to List<B>
which is handy.
Edit
After reading your last comment I think AutoMapper might be your solution.
You do not explicitly need to specify anything other than;
AutoMapper.CreateMap<A,B>();
Then you can map;
B b = Mapper.Map<A,B>(sourceA);
Edit 2
Or use reflection yourself and create an extension that takes A as an argument and copies the appropriate fields / properties from A to B.
Upvotes: 7
Reputation: 592
It won't work like this. You are making two different variables with almost same attributes inside ?! Why so?
You can cast common fields into base class ! It is the best way here.
Upvotes: 0