Helpful C# – OfType

In C#, the OfType method is used to filter a collection and retrieve only the elements that are of a specific type or that can be cast to a particular type. It is part of LINQ (Language-Integrated Query) and can be used with collections that implement the IEnumerable interface.

The syntax for using OfType is as follows:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<object> mixedList = new List<object>
        {
            1, "Hello", 2, "World", 3.14, true
        };

        IEnumerable<string> stringsOnly = mixedList.OfType<string>();

        foreach (string str in stringsOnly)
        {
            Console.WriteLine(str);
        }
    }
}

In this example, we have a mixed list of objects that include integers, strings, doubles, and a boolean value. We want to retrieve only the elements of type string from this collection.

  1. First, include the necessary using directives (using System;, using System.Collections.Generic;, and using System.Linq;).
  2. Create a list (mixedList) with a combination of different types.
  3. Use the OfType<string>() method on the mixedList to filter out only the elements that are of type string.
  4. Loop through the filtered collection (stringsOnly) using a foreach loop and print the strings to the console.

Output of the code will be:

Hello
World