I'm trying to output a value based on its type. Currently I'm creating a bunch of if-statements based on the type of T. Is there any better solution that makes the code look more concise?
public static void Output<T>(T data)
{
string dataStr = data.ToString();
if (typeof (T) == typeof(double))
{
dataStr = String.Format("{0:N4}", data);
}
Console.WriteLine(dataStr):
}
The only alternative is to avoid generics and provide explicit method overloads based on type:
public static void Output(Double data) { Console.WriteLine( "{0:N4}", data ); }
public static void Output(String data) { Console.WriteLine( "{0}", data ); }
public static void Output(Int32 data) { Console.WriteLine( "{0:G}", data ); }
// ...and so on
Note a downside to this approach is that overload selection is done at compile-time, not runtime, so this would fail: Output( (Object)someInt32Value );
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments