tags:

views:

68

answers:

3

Is it possible? With reflection or any other way?

A: 

it depends on the property. if it's a computed property - no, not unless you know what it's based on. if it's just an accessor to a private field, then you can try to modify the field.

in general, however, it's a very bad idea, as you likely have no knowledge of what side-effects this will cause.

kolosy
+1  A: 

As other stated, if you need to that, you're facing a design issue to begin with. Now, if you want to know if it's possible just for the sake of knowing, or if there's no other way on earth to do it, it's indeed possible, with the help of a very small helper library and an extension method.

Consider the following code:

class Person {

    int age;
    string name;

    public int Age { get { return age; } }
    public string Name { get { return name; } }
}

// ...

using Mono.Reflection;
using System.Reflection;

// ...

Person person = new Person (27, "jb");
PropertyInfo nameProperty = typeof (Person).GetProperty ("Name");
FieldInfo nameField = nameProperty.GetBackingField ();
nameField.SetValue (person, "jbe");

Using this code, you can get the backing field of a property with just the property, and assign a new value to the backing field. You can read more details about the implementation.

Also note that it works only for simple properties, such as:

public int Age { get { return age; } }

public string Name {
    get { return name; }
    set { name = value; }
}

public double Velocity { get; private set; }

If you have complex properties with custom code, the backing field resolver will fail.

Jb Evain
A: 

PropertyInfo isReadOnly = typeof System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance| BindingFlags.NonPublic);
isReadOnly.SetValue(param, false, null);//Remove the readonly property
.............put your code here

isReadOnly.SetValue(param, true, null);//Set readonly property

Bala