The answer to your question is Yes... it is possible. Your question indicates that the only difference is the return type (which is handled with generics), but that isn't true. The other difference is the TryParse function also relies on a type. So, you need a way to specify a type safe TryParse function which is handled with a delegate.
So, use a combination of generics and a delegate. Specify the type you want to use between the brackets. Define a delegate called TryParse which is also typed. Then, you can pass the function which does the parsing. I have included a complete example for a console application. If you look at the main, then it is a simple function call where you pass the proper TryParse function. What is cool about this method is that you can have TryParse for any type. If you create your own rational class or a fraction class, you can pass in the function for your class.
using System;
namespace DelegateSample
{
public class Program
{
// delegate to handle tryparse
public delegate bool TryParse<T>(string txt, out T desiredNumber);
// generic function that will get a number from a user and utilize the existing TryParse for the specified type
public static T GetNumberFromUser<T>(string info, TryParse<T> tryParseFunction)
{
T TheDesiredNumber;
while (true)
{
Console.Write("Please type " + info + " : ");
string input = Console.ReadLine();
// use the delegate here to run the TryParse, which is passed in
if (tryParseFunction(input, out TheDesiredNumber))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" - " + info + " is set to " + TheDesiredNumber.ToString() + "!");
Console.ForegroundColor = ConsoleColor.Gray;
return TheDesiredNumber;
}
// WrongInput isn't defined, this should suffice for the sample
Console.WriteLine(input + " - Invalid input!");
}
}
public static void Main(string[] args)
{
// this can be used for any function which implements the TryParse function which matches the delegate
// it is a simple function call. Specify the type between the brackets, and then pass the function in that
// does the TryParse. You could even write your own TryParse for your own classes, if needed.
int iVal = GetNumberFromUser<int>("integer", int.TryParse);
double dVal = GetNumberFromUser<double>("double", double.TryParse);
float fVal = GetNumberFromUser<float>("float", float.TryParse);
}
}
}