Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Assign an object from class B to class A

Tags:

c#

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 in class A

like image 410
sysuny fredrica Avatar asked Feb 05 '23 23:02

sysuny fredrica


2 Answers

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();
like image 96
InBetween Avatar answered Feb 08 '23 17:02

InBetween


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);
like image 36
denisv Avatar answered Feb 08 '23 16:02

denisv