Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the value of a read only property in C#

Tags:

c#

reflection

I'm trying to make a mod for a game in c# and I'm wondering if there's a way to change the value of a read only property using reflections.

like image 628
canhedian Avatar asked Nov 12 '15 19:11

canhedian


People also ask

How do you set the value of a read only property?

Assigning a Value. Code consuming a ReadOnly property cannot set its value. But code that has access to the underlying storage can assign or change the value at any time. You can assign a value to a ReadOnly variable only in its declaration or in the constructor of a class or structure in which it is defined.

What are the properties of read only?

A class property declared read-only is only allowed to be initialized once, and further changes to the property is not allowed. Read-only class properties are declared with the readonly keyword* in a typed property.

What is readonly function?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.

What is readonly in Objective C?

The readonly means simply that no setter method was synthesized, and therefore using the dot notation to set a value fails with a compiler error. The dot notation fails because the compiler stops you from calling a method (the setter) that does not exist.


2 Answers

In general, no.

Three examples:

public int Value { get { return _value + 3; } } // No

public int Value { get { return 3; } } // No

public int Value { get; private set; } // Yes

So, you can change the value of the property while this property has corresponding private, protected or internal field.

like image 66
Mark Shevchenko Avatar answered Nov 09 '22 01:11

Mark Shevchenko


You can in both those scenarios:

readonly int value = 4;

and

int value {get; private set}

using

typeof(Foo)
   .GetField("value", BindingFlags.Instance)
   .SetValue(foo, 1000); // (the_object_you_want_to_modify, the_value_you_want_to_assign_to_it)

You cannot modify

int value { get { return 4; } }

though.

If it returns a calculated value like

int value { get { return _private_val + 10; } }

you would have to modify _private_val accordingly.

like image 43
nozzleman Avatar answered Nov 09 '22 01:11

nozzleman