I'm wondering why C# doesn't just return a string when I index into a string like this :
string x = "xyz";
var c = x[0]
I'm wondering why C# doesn't just return a string when I index into a string like this :
string x = "xyz";
var c = x[0]
A string is made up of chars. If you're accessing a single element, as you're doing with the indexing operator, why should it return a string?
If you want a string to be returned you might want to use Substring.
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
Also see String class declaration.
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
Which is inherited by IEnumerable<char>
.
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; }
I don't really agree with the answers and comments stating that it was natural to return a char
. And no, a string in c# is not an array of char
by definition (see the first answer to the duplicate, it is a class of it's own.
The only reason a char
is returned is that the c# team decided to implement it that way. I don't know if they had a longer discussion about that or none at all. But I imagine that the reason for this implementation is that C# is more or less a successor of c/c++. And c/c++ developers have been highly used to this mental model of strings.
I rarely use the char
type in c# and guess I could live well with a string implementation with indexers returning strings (and maybe some GetCharAt ()
method) but others might then wonder why it is implemented like that.