Take the 2-minute tour ×

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 
                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 ?

share|improve this question
By the way, here is another treat regarding readonly fields, this time in structs... –  Greg Ros Jun 30 '12 at 18:38
add comment

1 Answer

up vote 5 down vote accepted

Yes, you can change the value of a readonly property at runtime through Reflection. And here's a very simple POC:

public class Program
    private static readonly string Foo = "Bar";

    static void Main()
            .GetField("Foo", BindingFlags.Static | BindingFlags.NonPublic)
            .SetValue(null, "new value");

When you run this console application it will print:

new value
share|improve this answer
Is it a thread to an application in that case? Does this case applies to constants as well. My belief are that we can't change constants because they are set at compile time and each dll maintains its own copy. Is that true? –  Shantanu Gupta Jun 30 '12 at 18:26
No, this doesn't apply to constants. They are baked at the metadata of the assembly at compile time and you cannot change their value at any possible means, not even with Reflection. As far as your first question whether this is a thread, did you mean threat? If you meant threat, then it will depend on the situation. –  Darin Dimitrov Jun 30 '12 at 18:27
add comment

Your Answer


