I want to set the value of LastName to null using reflection.
public void SetPropertyValueToNull(Type t)
{
PropertyInfo prop = t.GetProperty("LastName");
prop.SetValue(t, null, null);
}
I am passing typeof(User) as the parameter from another class where User is a model class which has LastName as one of the properties. It gives me Object does not match target type error.
How can I resolve this issue?
It gives me Object does not match target type error.
The first parameter of the SetValue
method is the object instance on which you want to set the property value.
You are passing t
itself as the first parameter which is of type Type
. You should instead pass an object that has a type equal to t
, e.g. User
in your specific case.
You should change your method to accept an object instance instead of a Type
and you can use it to get its type, get the property and then set its value.
So your method should look something like this:
public void SetPropertyValueToNull(object instance)
{
PropertyInfo prop = instance.GetType().GetProperty("LastName");
prop.SetValue(instance, null, null); //We need this overload for .NET < 4.5
}
This method will work for any object that has a writable property named LastName
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments