tags:

views:

127

answers:

5

Can the first char of a string be retrieved by doing the following?

MyString.ToCharArray[0]
+7  A: 

Just MyString[0]. This uses the String.Chars indexer.

Matthew Flaschen
+2  A: 

Mystring[0] should be enough

aqwert
Shouldn't 'a spent those extra five seconds typing the words, "should be enough".
Robert Harvey
Who answered this question first?
Craig Johnston
Select the oldest tab to see that it as Matthew
johnc
@johnc: Or better, hover over the timestamp.
Jeff M
A: 

Or you can to this

MyString[0];

james_bond
Yeah, I think that answer's been covered already.
Robert Harvey
@Robert, naw, I wanna see it one more time, just to be sure!
jjnguy
I just didn't see the ones before mine :)
james_bond
@james, no worries. I do it all the time too. I'm a really slow typer.
jjnguy
A: 

I think you are looking for this MyString.ToCharArray()[0]

:)

But you can use MyString[0] too.

Nayan
+1  A: 

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.

Jon Hanna