Wednesday 20 April 2011

Dot.Net: Set Property Value using Reflection

Question:
How can I set private properties of an object using reflection ?
How to set or get properties dynamically ?


Answer:
You can manipulate properties using reflection bypassing all access modifiers. (If security policy of your environment allows this)
This obviously breaks the OOP principle of encapsulation.
You usually do this when you want to create frameworks that use parameterized types and methods.

Let's say you have a class
public class Example
{
    public Example(string s)
    {
        this.Text = s;
    }
    public string Text { get; private set; }
}


Set property value
public void SetPropertyTest()
{
    Example ex = new Example("hello");

    // get public property on the type by name
    PropertyInfo pInfo = typeof(Example).GetProperty("Text");

    // set a value on a private property
    pInfo.SetValue(ex, ex.Text + " world II", null);

    Console.WriteLine("example = " + ex.Text);
    // => hello world II

}

Get property value
// once you have your propertyInfo, you just ask its value
    string s = pInfo.GetValue(ex, null);
}

happy programming ...

sunny day today! Vamos a la playa :)

going to the beach

No comments: