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

后端 未结 12 1828
無奈伤痛
無奈伤痛 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:33

    String is a class which takes an array of char to initialized itself, So when you try to fetch the element at some index it returns char. Check the string class

    public sealed class String : IComparable, ICloneable, IConvertible, IComparable, IEnumerable, IEnumerable, IEquatable
        {
            // Summary:
            //     Initializes a new instance of the System.String class to the value indicated
            //     by an array of Unicode characters.
            //
            // Parameters:
            //   value:
            //     An array of Unicode characters.
            [SecuritySafeCritical]
            public String(char[] value);
        }
    

    Also see String class declaration.

    public sealed class String : IComparable, ICloneable, IConvertible, IComparable, IEnumerable, IEnumerable, IEquatable
    

    Which is inherited by IEnumerable.

    Inside the string class there is a get property which returns the char when index is passed, see the image. Which clearly says that Gets the System.Char object at a specified position in the current System.String

    public char this[int index] { get; }
    

提交回复
热议问题