Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through an object and find the not null properties

I have 2 instances of the same objects, o1, and o2. If I am doing things like

 if (o1.property1 != null) o1.property1 = o2.property1 

for all the properties in the object. What would be the most efficient way to loop through all properties in an Object and do that? I saw people using PropertyInfo to check nulll of the properties but it seems like they could only get through the PropertyInfo collection but not link the operation of the properties.

Thanks.

like image 831
NewDTinStackoverflow Avatar asked Nov 03 '12 19:11

NewDTinStackoverflow


2 Answers

You can do this with reflection:

public void CopyNonNullProperties(object source, object target)
{
    // You could potentially relax this, e.g. making sure that the
    // target was a subtype of the source.
    if (source.GetType() != target.GetType())
    {
        throw new ArgumentException("Objects must be of the same type");
    }

    foreach (var prop in source.GetType()
                               .GetProperties(BindingFlags.Instance |
                                              BindingFlags.Public)
                               .Where(p => !p.GetIndexParameters().Any())
                               .Where(p => p.CanRead && p.CanWrite))
    {
        var value = prop.GetValue(source, null);
        if (value != null)
        {
            prop.SetValue(target, value, null);
        }
    }
}
like image 85
Jon Skeet Avatar answered Oct 05 '22 13:10

Jon Skeet


Judging from your example i think your looking for something like this:

static void CopyTo<T>(T from, T to)
{
    foreach (PropertyInfo property in typeof(T).GetProperties())
    {
        if (!property.CanRead || !property.CanWrite || (property.GetIndexParameters().Length > 0))
            continue;

        object value = property.GetValue(to, null);
        if (value != null)
            property.SetValue(to, property.GetValue(from, null), null);
    }
}
like image 21
Jan-Peter Vos Avatar answered Oct 05 '22 13:10

Jan-Peter Vos