Can the first char
of a string be retrieved by doing the following?
MyString.ToCharArray[0]
Can the first char
of a string be retrieved by doing the following?
MyString.ToCharArray[0]
I think you are looking for this MyString.ToCharArray()[0]
:)
But you can use MyString[0]
too.
The difference between MyString[0]
and MyString.ToCharArray()[0]
is that the former treats the string as a read-only array, while ToCharArray()
creates a new array. The former will be quicker (along with easier) for almost anything where it will work, but ToCharArray
can be necessary if you have a method that needs to accept an array, or if you want to change the array.
If the string isn't known to be non-null and non-empty you could do:
string.IsNullOrEmpty(MyString) ? null : (char?)MyString[0]
which returns a char?
of either null or the first character in the string, as appropriate.