I want to write a function that format int
and decimal
differently into string
I have this code:
and I want to rewrite it to generi
You could check the type of the variabele;
public static string FormatWithCommaSeperator<T>(T value)
{
if (value is int)
{
// Do your int formatting here
}
else if (value is decimal)
{
// Do your decimal formatting here
}
return "Parameter 'value' is not an integer or decimal"; // Or throw an exception of some kind?
}
DoFormat(int value)
{
}
DoFormat(double value)
{
}
If you insist on using generics:
switch (value.GetType().Name)
{
case "Int32":
break;
case "Double":
break;
default:
break;
}
OR
if (value is int)
{
int iValue = (int)(object)value;
}
else if (value is double)
{
double dValue = (double)(object)value;
}
else
{
}
Another way to do switch on generic is:
switch (typeof(T))
{
case Type intType when intType == typeof(int):
...
case Type decimalType when decimalType == typeof(decimal):
...
default:
...
}
In modern C#:
public static string FormatWithCommaSeperator<T>(T value) where T : struct
{
switch (value)
{
case int i:
return $"integer {i}";
case double d:
return $"double {d}";
}
}
Alternatively you could always do:
public static string FormatWithCommaSeparator<T>(T[] items)
{
var itemArray = items.Select(i => i.ToString());
return string.Join(", ", itemArray);
}
You could instead of using generics use IConvertible
public static string FormatWithCommaSeperator(IConvertible value) { IConvertible convertable = value as IConvertible; if(value is int) { int iValue = convertable.ToInt32(null); //Return with format. } ..... }