I have a List<object>
. I want to loop over the list and print the values out in a more friendly manner than just o.ToString()
in case some of the objects are booleans, or datetimes, etc.
How would you structure a function that I can call like MyToString(o)
and return a string formatted correctly (specified by me) for its actual type?
You can use the dynamic keyword for this with .NET 4.0, since you're dealing with built in types. Otherwise, you'd use polymorphism for this.
Example:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
List<object> stuff = new List<object> { DateTime.Now, true, 666 };
foreach (object o in stuff)
{
dynamic d = o;
Print(d);
}
}
private static void Print(DateTime d)
{
Console.WriteLine("I'm a date"); //replace with your actual implementation
}
private static void Print(bool b)
{
Console.WriteLine("I'm a bool");
}
private static void Print(int i)
{
Console.WriteLine("I'm an int");
}
}
Prints out:
I'm a date
I'm a bool
I'm an int
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