Think this is a generic vs type specific problem.
I would like to add a unit to a string casted argument that can be an int
or a float
.
I tried the following, but there is problem at the time of the cast because the type is not known at compile time.
namespace ConsoleApp17
{
class Program
{
static int myInt = 1;
static float myFloat = 2f;
static void Main(string[] args)
{
string myFloatStr = "1.3";
string myIntStr = "2";
Add<float>(myFloatStr, SetNewFloatValue);
Add<int>(myIntStr, SetNewIntValue);
Console.ReadLine();
}
public static void Add<T>(string str, Action<T> action)
{
T valueToSet = (T)Math.Round(double.Parse(str) + 1, 0 , MidpointRounding.AwayFromZero); //problem here, cannot convert double to T
action(valueToSet);
}
private static void SetNewFloatValue(float floatArg) {
myFloat += floatArg;
}
private static void SetNewIntValue(int intArg)
{
myInt += intArg;
}
}
}
fiddle in case its helpful.
Is method overload for each of the arguments the only solution for this, or is there a more elegant solution so that the same funtionality can be dealt with in the one same method for both types float
and int
?
Meaning that:
Add<float>(myFloatStr, SetNewFloatValue);
Add<int>(myIntStr, SetNewIntValue);
could be done with the one same method.
If you are using older versions than .Net 6, you can use Convert.ChangeType
for your case.
T valueToSet = (T)Convert.ChangeType(Math.Round(double.Parse(str) + 1, 0, MidpointRounding.AwayFromZero), typeof(T));