Is string actually an array of chars or does it just have an indexer?

后端 未结 12 1818
無奈伤痛
無奈伤痛 2020-12-06 09:58

As the following code is possible in C#, I am intersted whether string is actually an array of chars:

string a=\"TEST\";
char C=a[0]; // will be T

相关标签:
12条回答
  • 2020-12-06 10:07

    A string object contains a continuous block of characers, just like an array of characters, but the string object neither is, nor contains an array object.

    The compiler knows that the string string is immutable, so it can do certain optimisations when you access a string, in the same manner that it does optimisations when you access an array. So, when you access a string by index, it's likely that the code ends up accessing the string data directly rather than calling an indexer property.

    0 讨论(0)
  • 2020-12-06 10:10

    A string is not an array of chars until you convert it to one. The notation is simply used to access characters at different positions (indices) in a string.

    0 讨论(0)
  • 2020-12-06 10:11

    System.String is not a .NET array of Char because this:

    char[] testArray = "test".ToCharArray();
    
    testArray[0] = 'T';
    

    will compile, but this:

    string testString = "test";
    
    testString[0] = 'T';
    

    will not. Char arrays are mutable, Strings are not. Also, string is Array returns false, while char[] is Array returns true.

    0 讨论(0)
  • 2020-12-06 10:11

    Using Reflector, we can see that string does implement IEnumerable<char>. So, it is not a character array, but in essence can be used like one.

    public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
    

    EDIT:

    Implementing IEnumerable<char> does not mean that the type will be indexed. I didn't mean to convey that. It means that you can enumerate over it and use it like a collection. A better way of wording what I meant to say is that a string isn't a character array, but is a collection of characters. Thanks for the comment.

    0 讨论(0)
  • 2020-12-06 10:16

    Strings in .NET are backed by the System.String class, which internally uses a bunch of unsafe methods to do pointer manipulation on the actual string data using standard C memory manipulation techniques.

    The String class itself does not contain an array, but it does have an indexer property which allows you to treat the data as if it were an array.

    0 讨论(0)
  • 2020-12-06 10:20

    No, it's not an array. But it does have an indexer. Best of both worlds.

    0 讨论(0)
提交回复
热议问题