If you want one method to return different types of information, then I would use generics:
public static T GetInfo<T>(string name);
// This can be called as following:
string name = GetInfo<string>("name");
int salary = GetInfo<int>("salary");
There's one problem, though: Console.ReadLine returns a string, while our method could return any type. How can it convert a string to its 'target' type? You could check T and write custom logic for all types you want to support, but that's cumbersome and brittle. A better solution is to let the caller pass in a little function that knows how to transform a string into a specific type:
public static T GetInfo<T>(string name, Func<string, T> convert);
// This can be called as following:
string name = GetInfo<string>("name", s => s);
int salary = GetInfo<int>("salary", int.Parse);
Now how do you implement that method?
public static T GetInfo<T>(string name, Func<string, T> convert)
{
Console.WriteLine("Please enter " + name);
string input = Console.ReadLine();
return convert(input);
}
A few notes:
- Type parameters are often just named
T, but I find it useful to give them more descriptive names, such as TInfo.
- The
<string> and <int> parts can be left out in the second example, because the compiler has sufficient information to infer their types.
- I've left our error handling to keep the examples short and simple. In production code, you'll want to come up with a strategy to handle invalid input, though.