1

I want to see if I can make an instance of a class immutable even if the class itself isn't. What I have here is a similar situation to IntPtr.Zero and other static fields like that, except it's a mutable class and not a struct.

class TestClass
{
    public static readonly TestClass GoldStandard = new TestClass();
    public int field = 0;
}

class Program
{
    static void Main(string[] args)
    {
        TestClass test = TestClass.GoldStandard;

        test.field = 1; // I want to keep this from happening.

        Console.WriteLine(TestClass.GoldStandard.field);
    }
}

What can I do to keep GoldStandard from being modified?

EDIT: I regret that my question was so badly misunderstood. This is clearly not a duplicate of Immutable type and property in C# or How do I create an immutable Class?. Those questions are about how to create an immutable class, and not how to create an immutable instance of a mutable class.

As for Is there an easy way to make an immutable version of a class?, it certainly sounds very similar to my question. However, there are some important reasons it shouldn't count.

  1. The question asks how to make an instance immutable at some point during the instance's lifetime, rather than just having one instance of a mutable class be immutable from the start.
  2. The question asks how an immutable second class can be generated to mimic a mutable class, rather than having one mutable class act as immutable in a specific case.
  3. The answer to the question doesn't even address my question at all, and is mostly about how immutable classes work in general.

I understand moderators can't take too much time to understand the questions in depth when they're scanning for duplicates, but I hardly think it's fair for my question to be closed as a duplicate because of such superficial similarities.

Kyle Delaney
  • 11,616
  • 6
  • 39
  • 66
  • 2
    This question is clearly **NOT** a duplicate. Those "duplicates" make a whole class immutable, not a specific instance. – Alejandro Oct 27 '17 at 19:05
  • 1
    @Alejandro - see the [3rd link](https://stackoverflow.com/questions/26105608/is-there-an-easy-way-to-make-an-immutable-version-of-a-class), the first sentence of that question asks `Is there an easy way to make an instance immutable?` which is exactly what this question is asking. I do not see how this question is not a duplicate of that one. – Igor Oct 27 '17 at 19:08
  • Even if the 3rd link does count, the first two links should be removed. – Kyle Delaney Oct 27 '17 at 19:30
  • 1
    You can't do that in C#. This is [why classes like `ReadOnlyCollection` exist](https://msdn.microsoft.com/en-us/library/ms132474(v=vs.110).aspx). Your answer: ["You will have to explicitly design your types to be immutable."](https://stackoverflow.com/a/26105905/424129) – 15ee8f99-57ff-4f92-890c-b56153 Oct 27 '17 at 19:32

0 Answers0