Reputation: 1
C# won't let me cast a type T
to a type I can prove T
to be. How can I cast T
to that type?
public static T _cast<T> (object o) {
if (typeof(T) == typeof(string)) {
return (T) o.ToString(); // Compiler YELLS!
}
throw new InvalidCastException("missing compiler generated case");
}
I'm writing a program that generates code from C++ to C#. This _cast
operation I want to use in place of C++'s operator T ()
.
Upvotes: 1
Views: 134
Reputation: 7892
I think a more elegant solution than your double cast is using the as
keyword. Like this:
return o.ToString() as T;
I didn't try it, but the compiler shouldn't have an issue with that since it will return null when it can't cast the string to T, which within your conditional it won't do of course.
Upvotes: 3
Reputation: 8503
There's a difference between casting and parsing. I think what you want is to try and parse strings
int stringToNum = (int)"123"; //will not compile
int stringToNum2 = int.Parse("123");
Upvotes: 0
Reputation: 1
Normally I don't answer my own questions, but I just came up with the solution: downcast to object
before casting to T
public static T _cast<T> (object o) {
if (typeof(T) == typeof(string)) {
return (T)(object) o.ToString();
}
throw new InvalidCastException("missing compiler generated case");
}
Upvotes: 3
Reputation: 35870
There is no conversion from String to every other type. The compiler is telling you it doesn't know how to do what you've asked. If you provide more detail about what you're trying to do, maybe someone can offer some advice.
Upvotes: 0