I have Two Classes.
Class A:
public class A {
prop string p1 { get; set; }
prop string p2 { get; set; }
prop string p3 { get; set; }
}
Class B:
public class B {
prop string p1 { get; set; }
prop string p3 { get; set; }
}
Now assume we have an object from class B
and we want to assign it to object from class A
.
B b_obj = new B(){
p1 = "something",
p2 = "something else"
}
A a_obj = new A(){
p1 = b_obj.p1,
p3 = b_obj.p3,
}
I think the above solution is not best way.
What is best practice to assign b_obj
to another object from class A
?
Tip : All property in
class B
has a similar property inclass A
You can always implement an implicit or explicit cast operator:
public class B
{
public static explicit operator A(B b)
{
return new A() {
p1 = b_obj.p1,
p3 = b_obj.p3,
}
}
//...
}
And now, you can simply write any time you need an A
from a B
:
var a = (A)b;
If you don't have access to either A
or B
then you could implement an extension method:
public static A ToA(this B b)
{
return ...
}
And the use would be similar:
var a = b.ToA();
You can use automapper http://automapper.org/ Then you can use it like this:
AutoMapper.Mapper.CreateMap<A, B>();
var a = ...
var model = AutoMapper.Mapper.Map<B>(a);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With