A long time ago in a galaxy far, far away, I posted an answer to this question here about input and such.
The question dealt with avoiding multiple ReadLine() statements to get user input and a way around it to clean up code. I posted a simple answer with a prompt method that displayed the prompt and returned the input. However, it always returned the string. Now, one could implement their own parsing to extract the information they wanted, but what if Generics could simplify things and return the type desired?
I thought it would be easy. So I tried to do it as a simple exercise. Turns out, I don't think I'm smart enough (oops).
I first tried a helper method inside a Generic SomeClass<T>
like
public static T getInput(String prompt, Type T)
{
//some stuff about printing the prompt
String input = Console.In.ReadLine();
return (T)input;
}
As many of you will no doubt see, this is faulty and returns the error "cannot cast String to type T."
My next approach was to use SomeClass<T> where T : String
Again, many of you will see the fault here: String is sealed.
So: the question is, is there a way to use the method I've outlined and Generics to correctly grab user input and return it in the type requested, like int, String, or possibly a user-defined type?