Non-static method requires a target in PropertyInfo.SetValue

Victor Gil picture Victor Gil · Aug 26, 2010 · Viewed 14.3k times · Source

Ok, so I'm learning about generics and I'm trying to make this thing run, but its keep saying me the same error. Here's the code:

public static T Test<T>(MyClass myClass) where T : MyClass2
{
    var result = default(T);
    var resultType = typeof(T);
    var fromClass = myClass.GetType();
    var toProperties = resultType.GetProperties();

    foreach (var propertyInfo in toProperties)
    {
        var fromProperty = fromClass.GetProperty(propertyInfo.Name);
        if (fromProperty != null)
            propertyInfo.SetValue(result, fromProperty, null );
    }

    return result;
}

Answer

Ronald Wildenberg picture Ronald Wildenberg · Aug 26, 2010

This happens because default(T) returns null because T represents a reference type. Default values for reference types are null.

You could change your method to:

public static T Test<T>(MyClass myClass) where T : MyClass2, new()
{
    var result = new T();
    ...
}

and then it will work as you want it to. Of course, MyClass2 and its descendants must have a parameterless constructor now.