David.Chu.ca
David.Chu.ca

Reputation: 38644

How to use MethodInfo.Invoke to set property value?

I have a class with a property Value like this:

public class MyClass {
   public property var Value { get; set; }
   ....
}

I want to use MethodInfo.Invoke() to set property value. Here are some codes:

object o;
// use CodeDom to get instance of a dynamically built MyClass to o, codes omitted
Type type = o.GetType();
MethodInfo mi = type.GetProperty("Value");
mi.Invoke(o, new object[] {23}); // Set Value to 23?

I cannot access to my work VS right now. My question is how to set Value with a integer value such as 23?

Upvotes: 8

Views: 17131

Answers (2)

Thomas
Thomas

Reputation: 29522

If you are using .NET Framework 4.6 and 4.5, you can also use PropertyInfo.SetMethod Property :

object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetMethod.Invoke(o, new object[] {23});

Upvotes: 4

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

You can use the PropertyInfo.SetValue method.

object o;
//...
Type type = o.GetType();
PropertyInfo pi = type.GetProperty("Value");
pi.SetValue(o, 23, null);

Upvotes: 16

Related Questions