I created a following class within a namespace Global
namespace Global
{
public static class Status
{
public static readonly char Active;
public static readonly char Suspended;
public static readonly char Terminiated;
public static readonly char Deleted;
private static readonly Dictionary<char, string> statusCollection;
public static Dictionary<char, string> StatusCollection
{
get
{
return statusCollection;
}
}
static Status()
{
statusCollection = new Dictionary<char, string>();
statusCollection.Add('A', "Active");
statusCollection.Add('S', "Suspended");
statusCollection.Add('T', "Terminated");
statusCollection.Add('D', "Deleted");
Active = 'A';
Suspended = 'S';
Terminiated = 'T';
Deleted = 'D';
}
}
public class a
{
public void add()
{
//How to make this collection readonly
Status.StatusCollection.Add('N', "asd");
Status.Active = 'M'; //Throws a compile time exception, changes not allowed
}
}
}
Strange behaviour When I tried updating Status.Active in immediate window, I was expecting that value won’t change but changes were allowed. Does that mean we can change value of readonly variable via reflection or runtime ?
Yes, you can change the value of a
readonlyproperty at runtime through Reflection. And here’s a very simple POC:When you run this console application it will print: