Created
November 20, 2019 03:18
-
-
Save alfredmyers/4db8956990c32fbe4ddefab9ed595d96 to your computer and use it in GitHub Desktop.
Sample code demonstrating the difference between value types and reference types regarding the mutability of their readonly fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ConsoleApp2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var valueType = new ValueType(1); | |
Console.WriteLine(valueType.ReadOnlyField); | |
// was expecting maybe an error | |
valueType.GetType().GetField("ReadOnlyField").SetValue(valueType, 666); | |
Console.WriteLine(valueType.ReadOnlyField); | |
Console.WriteLine(); | |
var referenceType = new ReferenceType(2); | |
Console.WriteLine(referenceType.ReadOnlyField); | |
// but here, readonly is simply ignored | |
referenceType.GetType().GetField("ReadOnlyField").SetValue(referenceType, 666); | |
Console.WriteLine(referenceType.ReadOnlyField); | |
} | |
} | |
class ReferenceType | |
{ | |
public readonly int ReadOnlyField; | |
public ReferenceType(int value) => ReadOnlyField = value; | |
} | |
struct ValueType | |
{ | |
public readonly int ReadOnlyField; | |
public ValueType(int value) => ReadOnlyField = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
C#'s readonly field modifer is ignored by Reflection.
What I thought were differences in behavior between value- and reference-types was in fact a bug in the code above due to valueType being boxed (thus copied) on line 13 when passed to SetValue. As a result, the new value gets assigned to the copied object, not the original one.