Avalan
Avalan

Reputation: 159

Copy properties between structs

Is there a way to compare two instances of two different structs and if there are properties with the exact same name, have them copied from one instance to the other?

For example take the two structs:

struct typeA
{
 public byte ID;
 public byte distance;
 public byte time;
}

struct typeB
{
 public byte distance;
 public byte length;
}

variables are then created

 typeA A;
 typeB B;

next some values are assigned

 A.ID = 101;
 A.distance = 12;
 A.time = 5;

Now I want to compare variable A with B and if there are any properties with the same name (in this case 'distance' exist for both struct) copy them to the other variable. I don't want to use

 B.distance = A.distance

as I won't always know the names of the properties.

Does anybody have any ideas? Have only heard of Reflection, is that something to have a look at?

Upvotes: 1

Views: 104

Answers (3)

Denis Itskovich
Denis Itskovich

Reputation: 4523

Please note, that you are talking about properties, but your example code defines fields and not properties. Following extension method copies fields:

public static class Extensions
{
    public static void MergeFrom<TSource, TDestination>(this TDestination dest, TSource source)
    {
        var fieldPairs = typeof(TDestination)
            .GetFields()
            .Join(
                typeof(TSource).GetFields(),
                p => p.Name,
                a => a.Name,
                (bp, ap) => new { Source = bp, Destination = ap });
        foreach (var pair in fieldPairs)
        {
            pair.Destination.SetValue(dest, pair.Source.GetValue(source));
        }
    }
}

Upvotes: 1

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

I suggest you to use mapping tool for this. E.g. AutoMapper (avalable from NuGet)

Mapper.CreateMap<typeA, typeB>();
typeA A = new typeA { ID = 101, distance = 12, time = 5 };
typeB B = new typeB { length = 42 };
// ...
B = Mapper.Map(A, B);

With default mapping AutoMapper will map properties which have same names.

You should assign result of mapping back to B variable, because structs are value types and they passed by value. So, changes to passed copy of B will not affect original B variable. Result of code above is variable B with values:

{
  distance: 12,
  length: 42
}

Upvotes: 3

Paweł Bejger
Paweł Bejger

Reputation: 6366

You should take advantage of the AutoMapper.

Then you could use this in the following way:

Mapper.CreateMap<typeA, typeB>();

In case you would like to set some additional rules for the mapping process you could do this in the follownig way:

Mapper.CreateMap<typeA, typeB>()
   .ForMember(dest => dest.a, opt => opt.MapFrom(src => src.b));

Upvotes: 0

Related Questions