user7603510
user7603510

Reputation:

C# Assign an object from class B to class A

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

Upvotes: 2

Views: 3599

Answers (4)

Murad
Murad

Reputation: 543

First of all initialize B class and set values. Then create such a class:

public static void CopyPropertyValues(object source, object  destination)
{
var destProperties = destination.GetType().GetProperties();

foreach (var sourceProperty in source.GetType().GetProperties())
{
    foreach (var destProperty in destProperties)
    {
        if (destProperty.Name == sourceProperty.Name && 
    destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
        {
            destProperty.SetValue(destination, sourceProperty.GetValue(
                source, new object[] { }), new object[] { });

            break;
        }
    }
}

}

and pass A and B class to this class as Parameter

Upvotes: 0

fharreau
fharreau

Reputation: 2327

You can use AutoMapper (see denisv's answer) which provides mappings between classes based on name. You can then customize your mappings if you want to.

You can also write some extension methods:

public static class Extensions
{
    public A ToA(this B b)
    {
        return new A() 
        {
            p1 = b_obj.p1,
            p3 = b_obj.p3,
        };
    }
}

Upvotes: 2

denisv
denisv

Reputation: 319

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);

Upvotes: 1

InBetween
InBetween

Reputation: 32740

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();

Upvotes: 5

Related Questions