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 generics:
public static string FormatAsIntWithCommaSeperator(int value) { if (value == 0 || (value > -1 && value < 1)) return "0"; return String.Format("{0:#,###,###}", value); } public static string FormatAsDecimalWithCommaSeperator(decimal value) { return String.Format("{0:#,###,###.##}", value); } public static string FormatWithCommaSeperator<T>(T value) where T : struct { string formattedString = string.Empty; if (typeof(T) == typeof(int)) { if ((int)value == 0 || (value > -1 && value < 1)) return "0"; formattedString = String.Format("{0:#,###,###}", value); } //some code... } /// <summary> /// If the number is an int - returned format is without decimal digits /// </summary> /// <param name="value"></param> /// <returns></returns> public static string FormatNumberTwoDecimalDigitOrInt(decimal value) { return (value == (int)value) ? FormatAsIntWithCommaSeperator(Convert.ToInt32(value)) : FormatAsDecimalWithCommaSeperator(value); }
How can i use T in the function body?
What syntax should I use?
Generics provide the type checking at compile time . Finding bugs in compile-time can save time for debugging java program, because compile-time bugs are much easier to find and fix.
To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.
C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods, properties, events, delegates, and operators using the type parameter and without the specific data type.
You can use the TypeCode enum for switch:
switch (Type.GetTypeCode(typeof(T))) { case TypeCode.Int32: ... break; case TypeCode.Decimal: ... break; }
Since C# 7.0 you can use pattern matching:
switch (obj) { case int i: ... break; case decimal d: ... break; case UserDefinedType u: ... break; }
Beginning with C# 8.0 you can use switch expressions:
string result = obj switch { int i => $"Integer {i}", decimal d => $"Decimal {d}", UserDefinedType u => "User defined {u}", _ => "unexpected type" };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With