简体   繁体   中英

Why does C# string have a title “Immutable” if to compare it with F# analogue?

I have read the older topics like those ones:

But, I can't understand the meaning of the word immutable , if to compare it with the F# analogue:

open System
let data = "London"
data <- "123"
Console.WriteLine data

This one won't compile due the next reason:

error FS0027: This value is not mutable. Consider using the mutable keyword, eg 'let mutable data = expression'.

So... If to compare the F# behaviour with the C# one, seems to be F# has the real meaning of immutability or I don't understand the real meaning of this term...

Let's look at the C# variant:

class Program
{
    static void Main()
    {
        var a = "London";
        a = "123";
        System.Console.WriteLine(a);
    }
}

The output will be: 123 .

Let's take information from the next article: Why are the strings immutable in .NET?

字符串附加

Honestly, if to look at this picture and compare it with the F# variant, I can't see the immutability... But also, I understand, that over 100+ people at SO (questions were published at the top of this question) can't be wrong and give the wrong name for such meaning.

Please, tell me why has been the C# string called immutable , if I can change its value? And if to compare it with the F# sample, the results are different for the single meaning.

You are confusing the immutability of the variable in F# with the immutability of the object in C#.

In C#, you can change which object representing a string a variable is pointing at. But you can't change anything about that object, hence the object is immutable.

In F#, you cannot change which value a variable has, so the variable is also immutable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM