Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set value of property where there is no setter

I have seen various questions raised and answered where we can invoke a private setter using reflection such as this one:

Is it possible to get a property's private setter through reflection?

However I have some code which has a property i need to set but cant because there is no setter, I cant add a setter as this isn't my code. Is there a way to somehow set the value using reflection in this scenario?

like image 536
Luke De Feo Avatar asked Dec 18 '13 18:12

Luke De Feo


People also ask

How do you set property value?

To set the value of an indexed property, call the SetValue(Object, Object, Object[]) overload. If the property type of this PropertyInfo object is a value type and value is null , the property will be set to the default value for that type.

How to call getter and setter methods in c#?

From the outside, the syntax for accessing getters and setters is indistinguishable from that of accessing variables. Assignments translate into calls of setters, while plain expression uses translate into calls of getters. In intellisense, the list of getters and setters should open upon placing a dot .

What is the importance of using properties in ac program?

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.


2 Answers

I do not suggest doing this on your application but for testing purpose it may be usefull...

Assuming you have:

public class MyClass
{
     public int MyNumber {get;}
}

You could do this if its for test purpose, I would not suggest to use this in your runtime code:

var field = typeof(MyClass).GetField("<MyNumber>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(anIstanceOfMyClass, 3);
like image 58
Abyte0 Avatar answered Oct 03 '22 23:10

Abyte0


You have to keep in mind that a property is just syntactic sugar for a pair of methods. One method (the getter) returns a value of the property type and one method (the setter) accepts a value of the property type.

There is no requirement that the getter and setter actually get or set anything. They're just methods, so they're allowed to do anything. The only requirement is that the getter return a value. From the outside there's no way you can really tell if there is a backing field. The getter could be getting computed every time it's called. It may be based on other properties.

So, no, there isn't really any way in general to "set" a property that doesn't have a setter.

like image 31
Kyle Avatar answered Oct 03 '22 23:10

Kyle