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.
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With