Skip to content

Compiler allows assignment to const field #9785

@zanaptak

Description

@zanaptak

Given C# code with a const (and readonly for comparison):

public class Class1
{
    public const string MyConst = "my const";
    public static readonly string MyReadonly = "my readonly";
}

F# compiler allows assignment to the const (leaving it to fail at runtime):

Class1.MyConst <- "changed" // compiler allows this
Class1.MyReadonly <- "changed" // FS0690: This field is readonly

Note that C# compiler disallows:

Class1.MyConst = "changed"; // CS0131: The left-hand side of an assignment must be a variable, property or indexer
Class1.MyReadonly = "changed"; // CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)

Repro steps

Create C# class library project with:

namespace ClassLibrary1
{
    public class Class1
    {
        public const string MyConst = "my const";
        public static readonly string MyReadonly = "my readonly";
        void Test()
        {
            // Uncomment for C# compiler errors
            // Class1.MyConst = "changed";
            // Class1.MyReadonly = "changed";
        }
    }
}

Create F# project referencing above C# project, with:

open ClassLibrary1
Class1.MyConst <- "changed" // compiler allows this
Class1.MyReadonly <- "changed" // FS0690: This field is readonly

Expected behavior

F# compiler should prevent assignment to const at compile time.

Actual behavior

F# compiler allows assignment to const at compile time.

Related information

  • Operating system: Windows 10
  • .NET Runtime kind (.NET Core, .NET Framework, Mono): .NET Core 3.1.302
  • Editing Tools (e.g. Visual Studio Version, Visual Studio): Visual Studio 2019 16.6.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions