C# Generic Collections for Multiple Types

In C#, you can use generic collections to store objects of different types. You can achieve this by using the generic classes List or Dictionary. Here is an example that demonstrates how to use List to store objects of different types:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<object> objects = new List<object>();

        objects.Add(10);
        objects.Add("Hello");
        objects.Add(3.14);

        foreach (var obj in objects)
        {
            if (obj is int)
            {
                Console.WriteLine($"Integer: {obj}");
            }
            else if (obj is string)
            {
                Console.WriteLine($"String: {obj}");
            }
            else if (obj is double)
            {
                Console.WriteLine($"Double: {obj}");
            }
        }
    }
}

In this example, we created a List object that can store objects of any type. We added an integer, a string, and a double-precision floating point number to the list. Then, we iterate over the list and perform different operations based on the type of the object. You can also use Dictionary to store objects of different types, just set the types of the key and value to object.

bannerAds