3

I have a char type column in table. I want to convert it to a char in C#. It is working by

char gender = Convert.ToChar(dataRow["Gender"]);

But it failed

 char gender = (char)(dataRow["Gender"]);

If a column is int type. I can use (int) to cast an object. Why it failed on char(exception)?

InValidCastException.

Thanks,

5 Answers5

3

The datarow[column] is an expression of type 'object'

The Convert.ToChar() method has an overload that takes an object as argument, so the compiler knows what to do.

The (char)dataRow[column] is an explicit cast of dataRow[column] to the char type, but an automatic conversion from object to char doesn't exist

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Do you mean (char) take a char object as an argument? –  Jun 18 '12 at 15:03
  • The compiler doesn't complain. I think you mean the runtime. Also the issue comes from trying to unbox as a different type. See http://stackoverflow.com/a/1085105/442078 – Will Jun 18 '12 at 15:28
1

Convert.ToChar reads the text value "A" and converts it into a character object with the value "A".

Casting assumes the original value IS a character object. The error tells you it is not.

John Arlen
  • 6,539
  • 2
  • 33
  • 42
1

Apparently dataRow["Gender"]) contains an int value. This means it's a "boxed" int (an 'int' stored as an object). You can only cast that to a "real" int, you can't directly convert it to something else, like a char.

You can however use a two-step approach:

char gender = (char)(int)dataRow["Gender"];
  • first cast the boxed int ro a real one
  • then convert that int to a char.
Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
0

Most probabbly the real value in the cell is of type object. In this case you will get InvalidCastException.

Convert.ToChar works, instead, cause there is an overload that accepts object type.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

If dataRow["Gender"] is in fact a (strongly typed) string, you could use

char g = dataRow["Gender"][0];

to get the zeroth character of that string (would fail if the string was null or empty). If, on the other hand, dataRow["Gender"] is a string but is typed as System.Object, you could use

char g = ((string)dataRow["Gender"])[0];
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181