Why are const parameters not allowed in C#?

后端 未结 5 1158
借酒劲吻你
借酒劲吻你 2020-11-28 02:49

It looks strange especially for C++ developers. In C++ we used to mark a parameter as const in order to be sure that its state will not be changed in the method

5条回答
  •  无人及你
    2020-11-28 03:31

    This is possible since C# 7.2 (December 2017 with Visual Studio 2017 15.5).

    For Structs and basic types only!, not for members of classes.

    You must use in to send the argument as an input by reference. See:

    See: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/in-parameter-modifier

    For your example:

    ....
    static void TestMethod1(in MyStruct val)
    {
        val = new MyStruct;  // Error CS8331 Cannot assign to variable 'in MyStruct' because it is a readonly variable
        val.member = 0;  // Error CS8332 Cannot assign to a member of variable 'MyStruct' because it is a readonly variable
    }
    ....
    static void TestMethod2(in int val)
    {
        val = 0;  // Error CS8331 Cannot assign to variable 'in int' because it is a readonly variable
    }
    ....
    

提交回复
热议问题