What is the difference between a mutable and immut

2019-01-02 19:55发布

What is the difference between a mutable and immutable string in C#?

标签: c# string
14条回答
路过你的时光
2楼-- · 2019-01-02 20:08

Strings are mutable because .NET use string pool behind the scene. It means :

string name = "My Country";
string name2 = "My Country";

Both name and name2 are referring to same memory location from string pool. Now suppose you want to change name2 to :

name2 = "My Loving Country";

It will look in to string pool for the string "My Loving Country", if found you will get the reference of it other wise new string "My Loving Country" will be created in string pool and name2 will get reference of it. But it this whole process "My Country" was not changed because other variable like name is still using it. And that is the reason why string are IMMUTABLE.

StringBuilder works in different manner and don't use string pool. When we create any instance of StringBuilder :

var address  = new StringBuilder(500);

It allocate memory chunk of size 500 bytes for this instance and all operation just modify this memory location and this memory not shared with any other object. And that is the reason why StringBuilder is MUTABLE.

I hope it will help.

查看更多
大哥的爱人
3楼-- · 2019-01-02 20:09

Mutable and immutable are English words meaning "can change" and "cannot change" respectively. The meaning of the words is the same in the IT context; i.e.

  • a mutable string can be changed, and
  • an immutable string cannot be changed.

The meanings of these words are the same in C# / .NET as in other programming languages / environments, though (obviously) the names of the types may differ, as may other details.


For the record:

  • String is the standard C# / .Net immutable string type
  • StringBuilder is the standard C# / .Net mutable string type

To "effect a change" on a string represented as a C# String, you actually create a new String object. The original String is not changed ... because it is unchangeable.

In most cases it is better to use String because it is easier reason about them; e.g. you don't need to consider the possibility that some other thread might "change my string". However, when you need to construct or modify a string using a sequence of operations, it may be more efficient to use a StringBuilder.


And finally, for those people who assert that a StringBuilder is not a string because it is not immutable, the Microsoft documentation describes StringBuilder thus:

"Represents a mutable string of characters. This class cannot be inherited."

查看更多
唯独是你
4楼-- · 2019-01-02 20:09

To clarify there is no such thing as a mutable string in C# (or .NET in general). Other langues support mutable strings (string which can change) but the .NET framework does not.

So the correct answer to your question is ALL string are immutable in C#.

string has a specific meaning. "string" lowercase keyword is merely a shortcut for an object instantiated from System.String class. All objects created from string class are ALWAYS immutable.

If you want a mutable representation of text then you need to use another class like StringBuilder. StringBuilder allows you to iteratively build a collection of 'words' and then convert that to a string (once again immutable).

查看更多
时光乱了年华
5楼-- · 2019-01-02 20:10

None, actually. The String class is mutable.

unsafe
{
    string foo = string.Copy("I am immutable.");
    fixed (char* pChar = foo)
    {
        char* pFoo = pChar;

        pFoo[5] = ' ';
        pFoo[6] = ' ';
    }

    Console.WriteLine(foo); // "I am   mutable."
}

This kind of logic is done all the time in the String and StringBuilder classes, actually. They just allocate a new string each time you call Concat, Substring, etc. and use pointer arithmetic to copy over to the new string. Strings just don't mutate themselves, hence why they are considered "immutable".


By the way, do not attempt this with string literals or you will badly mess up your program:

string bar = "I am a string.";

fixed (char* pChar = bar)
{
    char* pBar = pChar;

    pBar[2] = ' ';
}

string baz = "I am a string.";

Console.WriteLine(baz); // "I  m a string."

This is because string literals are interned in the desktop .NET Framework; in other words, bar and baz point to the exact same string, so mutating one will mutate the other. This is all fine and dandy though if you're using an unmanaged platform like WinRT, which lacks string interning.

查看更多
不流泪的眼
6楼-- · 2019-01-02 20:13

String in C# is immutable. If you concatenate it with any string, you are actually making a new string, that is new string object ! But StringBuilder creates mutable string.

查看更多
时光乱了年华
7楼-- · 2019-01-02 20:19

Here is the example for Immutable string and Mutable string builder

        Console.WriteLine("Mutable String Builder");
        Console.WriteLine("....................................");
        Console.WriteLine();
        StringBuilder sb = new StringBuilder("Very Good Morning");
        Console.WriteLine(sb.ToString());
        sb.Remove(0, 5);
        Console.WriteLine(sb.ToString());

        Console.WriteLine();

        Console.WriteLine("Immutable String");
        Console.WriteLine("....................................");
        Console.WriteLine();
        string s = "Very Good Morning";
        Console.WriteLine(s);
        s.Substring(0, 5);
        Console.WriteLine(s);
        Console.ReadLine();
查看更多
登录 后发表回答