c# – Select type via switch?

Question:

How to select type via switch in c # 7? How would the following example be written through a switch?

var items = new object[] { 1, "tt", DateTime.UtcNow };

foreach (var item in items)
{
    if (item is int)
        Console.WriteLine((int)item);
    else if (item is string)
        Console.WriteLine("'" + ((string)item).Replace("'", "''") + "'");
    else if (item is DateTime)
        Console.WriteLine("'" + ((DateTime)item).ToString("O") + "'");
}

The next option doesn't work. It throws errors that the variables i, s and date are not known:

foreach (var item in items)
{
    switch (item)
    {
        case item is int i:
            Console.WriteLine(i);
            break;
        case item is string s:
            Console.WriteLine("'" + s.Replace("'", "''") + "'");
            break;
        case item is DateTime date:
            Console.WriteLine("'" + date.ToString("O") + "'");
            break;
    }
}

Through if works:

foreach (var item in items)
{
    if (item is int i)
        Console.WriteLine(i);
    else if (item is string s)
        Console.WriteLine("'" + s.Replace("'", "''") + "'");
    else if (item is DateTime date)
        Console.WriteLine("'" + date.ToString("O") + "'");
}

Answer:

foreach (var item in items)
{
    switch (item)
    {
        case int i:
            Console.WriteLine(i);
            break;
        case string s:
            Console.WriteLine("'" + s.Replace("'", "''") + "'");
            break;
        case DateTime date:
            Console.WriteLine("'" + date.ToString("O") + "'");
            break;
    }
}
Scroll to Top