Using System.Reflection in C# on an object to set a property value

Last post 07-03-2009 7:38 AM by FoolongC. 2 replies.

Sort Posts:

  • Using System.Reflection in C# on an object to set a property value

    07-01-2009, 10:20 PM
    • Member
      46 point Member
    • FoolongC
    • Member since 08-23-2007, 9:12 PM
    • Posts 80

    Hi all,

    Can anyone post an example of reflecting on an object and if I find a property in that object then setting that property's value and then returning the object.

    I want to create a method that takes an object and a string that represents the property I want to set.

    Thanks in advance.


  • Re: Using System.Reflection in C# on an object to set a property value

    07-01-2009, 11:18 PM
    • Contributor
      4,992 point Contributor
    • RickNZ
    • Member since 01-01-2009, 8:43 AM
    • Nelson, New Zealand
    • Posts 836

    Your code will look something like this:

    PropertyInfo pinfo = typeof(YourClass).GetProperty(key);
    MethodInfo setInfo = pinfo.GetSetMethod(true);
    if (setInfo != null)
        setInfo.Invoke(null, param);


  • Re: Using System.Reflection in C# on an object to set a property value

    07-03-2009, 7:38 AM
    Answer
    • Member
      46 point Member
    • FoolongC
    • Member since 08-23-2007, 9:12 PM
    • Posts 80

    This is what I'm looking for and will work. Thank you!

Page 1 of 1 (3 items)