Anyname Donotcare
Anyname Donotcare

Reputation: 11423

Converting from string to character

Q:

When i convert from string to character through the following line of code.

 grp.EntireClass = char.Parse(record[3]);

I get the following value:: 49'1'


Upvotes: 0

Views: 412

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504152

I suspect you don't actually get "49'1'" - that's probably just how the debugger's showing it.

A simpler way though is:

string text = record[3]; // I assume...
grp.EntireClass = text[0]; // Gets the first character of text

This is equivalent to:

grp.EntireClass = record[3][0];

I split it out in the first version just for clarity.

You may well want to check that text is not:

  • Null
  • Empty
  • More than one character

In the first two cases the above code will throw an exception; in the third case it would just ignore everything after the first character.

Upvotes: 5

What is the type of record and record[3] ? If record is a string, why call Parse at all - you can just read record[3] and it would be a char. If record[3] itself is a string, use record[3][0] (for example).

Upvotes: 1

Related Questions