Assignment of new value to immutable value structs in C++/CLI
<p>It is often recommended to use immutable structs in .NET programming, since using mutable structs sets one up for simple mistakes. However, when I attempt to assign a new value by instantiating a new struct, I get error C3892 in C++ yet the equivalent code in C# has no issue. This is a problem because this prevents me from initializing an array of immutable structs. </p>

<p>The issue is easily worked around by using a readonly property instead of a field, but I would like to know why I cannot do the same thing in C++/CLI as in C#. Am I doing something wrong, or is this simply a limitation (or bug) in C++/CLI? Is there any way to make use of arrays of immutable structs in C++/CLI or must I avoid them?</p>

<p>C++ Header (named "AnnoyingCppBug.h"):</p>

<pre><code>using namespace System;

namespace AnnoyingCppBug {

    public value struct immutableType
    {
        const int Value;

        immutableType(int value)
            : Value(value) {}
    };

    public value struct immutableWorkaround
    {
        property int Value
        {
            int get() { return _value; }
        }

        immutableWorkaround(int value)
            : _value(value) {}
    private:
        int _value;
    };

    public value struct mutableType
    {
        int Value;

        mutableType(int value)
            : Value(value) {}
    };

    public value struct Class1 abstract sealed
    {
        static void Test();
    };
}
</code></pre>

<p>C++ Source File:</p>

<pre><code>#include "stdafx.h"

#include "AnnoyingCppBug.h"

namespace AnnoyingCppBug {
    void Class1::Test()
    {
        auto imm1 = immutableType(0);
        auto imm2 = immutableWorkaround(0);
        auto imm3 = mutableType(0);

        imm1 = immutableType(1);    // error C3892: 'arr1': you cannot assign to a variable that is const
        imm2 = immutableWorkaround(1);
        imm3 = mutableType(1);

        // The reason this matters is because I need to initialize an array:
        auto arr = gcnew array&lt;immutableType&gt;(1);
        arr[0] = immutableType(0);  // error C3892: 'arr1': you cannot assign to a variable that is const
    }
}
</code></pre>

<p>C# Code that does the same but builds fine:</p>

<pre><code>    struct immutableType
    {
        public readonly int Value;
        public immutableType(int value)
        {
            Value = value;
        }
    }

    static void Test()
    {
        var imm = new immutableType(0);
        imm = new immutableType(1);
        var arr = new immutableType[1];
        arr[0] = new immutableType(1);
    }
</code></pre>