Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Switch on Object Type at Runtime

Tags:

c#

.net

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?

like image 445
Davis Dimitriov Avatar asked Jan 19 '23 22:01

Davis Dimitriov


1 Answers

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
like image 75
wsanville Avatar answered Jan 31 '23 03:01

wsanville