Set object property using reflection

298,883

Solution 1

Yes, you can use Type.InvokeMember():

using System.Reflection;
MyObject obj = new MyObject();
obj.GetType().InvokeMember("Name",
    BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
    Type.DefaultBinder, obj, "Value");

This will throw an exception if obj doesn't have a property called Name, or it can't be set.

Another approach is to get the metadata for the property, and then set it. This will allow you to check for the existence of the property, and verify that it can be set:

using System.Reflection;
MyObject obj = new MyObject();
PropertyInfo prop = obj.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
if(null != prop && prop.CanWrite)
{
    prop.SetValue(obj, "Value", null);
}

Solution 2

You can also do:

Type type = target.GetType();

PropertyInfo prop = type.GetProperty("propertyName");

prop.SetValue (target, propertyValue, null);

where target is the object that will have its property set.

Solution 3

Reflection, basically, i.e.

myObject.GetType().GetProperty(property).SetValue(myObject, "Bob", null);

or there are libraries to help both in terms of convenience and performance; for example with FastMember:

var wrapped = ObjectAccessor.Create(obj); 
wrapped[property] = "Bob";

(which also has the advantage of not needing to know in advance whether it is a field vs a property)

Solution 4

Or you could wrap Marc's one liner inside your own extension class:

public static class PropertyExtension{       

   public static void SetPropertyValue(this object obj, string propName, object value)
    {
        obj.GetType().GetProperty(propName).SetValue(obj, value, null);
    }
}

and call it like this:

myObject.SetPropertyValue("myProperty", "myValue");

For good measure, let's add a method to get a property value:

public static object GetPropertyValue(this object obj, string propName)
{
        return obj.GetType().GetProperty(propName).GetValue (obj, null);
}

Solution 5

Use somethings like this :

public static class PropertyExtension{       

   public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
   {
    PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
    property.SetValue(p_object, Convert.ChangeType(value, property.PropertyType), null);
   }
}

or

public static class PropertyExtension{       

   public static void SetPropertyValue(this object p_object, string p_propertyName, object value)
   {
    PropertyInfo property = p_object.GetType().GetProperty(p_propertyName);
    Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
    object safeValue = (value == null) ? null : Convert.ChangeType(value, t);

    property.SetValue(p_object, safeValue, null);
   }
}
Share:
298,883
Renan Rodrigues
Author by

Renan Rodrigues

Updated on July 08, 2022

Comments

  • Renan Rodrigues
    Renan Rodrigues almost 2 years

    Is there a way in C# where I can use reflection to set an object property?

    Ex:

    MyObject obj = new MyObject();
    obj.Name = "Value";
    

    I want to set obj.Name with reflection. Something like:

    Reflection.SetProperty(obj, "Name") = "Value";
    

    Is there a way of doing this?

  • Shivang Gangadia
    Shivang Gangadia about 15 years
    I have done this very same thing today. The above works great, obviously a null check should be done on prop before attempting to use it.
  • halfpastfour.am
    halfpastfour.am over 12 years
    Wow, got a little confused from the merge, but i found your answer again! Thank you, you deserve an 'accept', but since my thread is merged :( Thanks again!
  • LostNomad311
    LostNomad311 almost 12 years
    If you aren't dealing with all strings you might wanna convert the data first: var val = Convert.ChangeType(propValue, propInfo.PropertyType); source: devx.com/vb2themax/Tip/19599
  • Sudhanshu Mishra
    Sudhanshu Mishra over 10 years
    @MarcGravell, I was looking at FastMember and it is pretty interesting. Is there a getting started/tutorial somewhere for us mere mortals to use this great lib of yours?
  • ThreeFx
    ThreeFx over 9 years
    Hi and welcome to Stack Overflow. Please format your code properly and not just dump it in your post, it will help others understand your answer.
  • x19
    x19 over 9 years
    How can I get the type of property by FastMember?
  • Marc Gravell
    Marc Gravell over 9 years
    @Jahan accessor => GetMembers => Member => Type
  • j.i.h.
    j.i.h. over 9 years
    @AntonyScott I would think you'd want to know if you're invoking the wrong property, so "fail silently" seems like a bad course.
  • Shivang Gangadia
    Shivang Gangadia over 9 years
    @j.i.h. I can see your point, but it depends on the situation really.
  • Marc
    Marc over 8 years
    The part where you get the property type and then cast it was really useful for me. It works like a charm. Thank you
  • Bastiaan
    Bastiaan almost 8 years
    great answer! The good thing about a oneliner is that it is much faster to understand, since there are no user named variables in between which for yourself might not make any sense..
  • tecfield
    tecfield almost 7 years
    alternatively, you can use obj.GetType().GetProperty("Name")?.GetSetMethod()?.Invoke(..‌​.)
  • T.Todua
    T.Todua about 6 years
    its impossible to set value for CanWrite=False types, right?