jaekie
jaekie

Reputation: 2303

How do I populate current class with new class values?

This one is a little difficult to explain so I'll show code first..

Note: Made example less confusing

public class Class1
{
     public string Title {get;set;}
     public string Name {get;set;}


     public Class1(Class1 class1)
     {
         // ?? How do I populate current class with new class values?
         // ?? this = class1;  - Does not work
         // I want to avoid having to manually set each value
     }
}

Thanks for help.. here what I did.. Created this in my extension class.. so I can now do

Extensions.MapValues(class1, this);

    public static void MapValues(object from, object to)
    {
        var fromProperties = from.GetType().GetProperties();
        var toProperties = to.GetType().GetProperties();

        foreach (var property in toProperties) {
            var fromProp = fromProperties.SingleOrDefault(x => x.Name.ToLower() == property.Name.ToLower());

            if(fromProp == null) {
                continue;
            }

            var fromValue = fromProp.GetValue(from, null);
            if(fromValue == null) {
                continue;
            }

            property.SetValue(to, fromValue, null);
        }
    }


Upvotes: 1

Views: 310

Answers (2)

Randolpho
Randolpho

Reputation: 56448

It'll probably be easier to manually set each value.

That said, if the column name of the DataRow is the same for each property in your class, and if the types are equally the same, you could use Reflection to set the property name. You would do it somewhat like this:

public Class1(DataRow row)
{
    var type = typeof(Class1);
    foreach(var col in row.Table.Columns)
    {
        var property = type.GetProperty(col.ColumnName);
        property.SetValue(this, row.Item(col), null);
    }
}

Upvotes: 1

SLaks
SLaks

Reputation: 888203

You can't.

You can either manually copy over the properties, or replace the constructor with a static factory method that returns row.ToClass1().

Upvotes: 5

Related Questions