I've been messing around with generic methods for my own console applications, because some operations just seemed really common to me. I'm currently wandering if there's a way to constrain a method's input type to a specific set of types in hard code by means of listing/methods that they contain, which could mean that I don't have to suppress warnings in my code if the assumption is there. Here's my current code:
static T GetNumber<T>() where T : new()
{
Type type = typeof(T);
MethodInfo TryParse = (from item in type.GetMethods() where item.Name == "TryParse" select item).ElementAt(0);
while(true)
{
string input = NotNullInput();
object[] parameters = new object[] { input, new T() };
#pragma warning disable CS8605
if (!(bool)TryParse.Invoke(new T(), parameters))
Console.WriteLine($"Invalid {type.Name} input");
else
return (T)parameters[1];
#pragma warning restore CS8605
}
}
Just makes sure the user puts in the correct format, and I know that it would probably only ever be used on types like int, float, double, long etc. I know all the types I've thought of using contained the TryParse method, so if there's a way to assume that, it would fix everything.
Also open to suggestions on how to improve the code because I'm still learning how to mess around with types and reflection.