I have this method:

public static T To<T>(this char o) where T : struct { return (T)Convert.ChangeType(o, typeof(T)); } 

If I InvalidCastException double (or float) in place of T, then an InvalidCastException is issued with a text like System.InvalidCastException: Недопустимое приведение "Char" к "Double". So what's wrong with double? The type is clearly greater than char. Now this method looks like this:

 public static T To<T>(this char o) where T : struct { var obj = Convert.ChangeType(o, typeof(int)); return (T)Convert.ChangeType(obj, typeof(T)); } 

The question itself is in the title. Is this somehow explained somewhere in terms of logic? I did not find the answer.

1 answer 1

The Convert.ChangeType method internally attempts to bring the argument to IConvertible and call the appropriate method.

For a Char case, its method will be called .ToDouble

 /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double")); } 

In which an exception is clearly thrown.


Why is the .ToDouble method not supported?

Not only this method. .ToBoolean , .ToDateTime , .ToDecimal and .ToSingle also not supported, they all throw InvalidCastException as well as .ToDouble .

In this case, the .NET design tries to save you from problems. Converting char to integer types makes sense, you can look at the Unicode tables and count the number of codepoint . But what should convert to Boolean mean? Which Unicode code point will be True ? How can a symbol be a fractional value at all? No half or quarter codepoint .

translation of the answer @HansPassant


It is also worth noting that the type char can be implicitly converted to type ushort , int , uint , long , ulong , float , double or decimal .

That is, the following code will work without errors:

 char c = 'c'; double a = (double)c; double b = c; 
  • Well, a great complete answer. Only to 'double' and similar 'char' is converted only explicitly. - Victor Gorban
  • @VictorGorban, what does it mean explicitly ? :-) usually under the implicit conversion means the possibility of executing the following code: double b = c; where c char variable is simply assigned, and not explicitly converted to double . - Grundy
  • I mixed up, I apologize. Thanks again for the complete answer. - Victor Gorban