Reputation:
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,
Upvotes: 3
Views: 8735
Reputation: 216313
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
Upvotes: 3
Reputation: 39329
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"];
int
ro a real onechar
.Upvotes: 2
Reputation: 61992
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];
Upvotes: 0
Reputation: 62276
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.
Upvotes: 0
Reputation: 6699
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.
Upvotes: 1