Skip to content

Instantly share code, notes, and snippets.

@alfredmyers
Created November 20, 2019 03:18
Show Gist options
  • Save alfredmyers/4db8956990c32fbe4ddefab9ed595d96 to your computer and use it in GitHub Desktop.
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
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;
}
}
@alfredmyers
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment