C# OfType Example

LINQ (language integrated query)

OfType searches for elements by their types. The System.Linq namespace provides this generic method to test derived types. By using the OfType method, we declaratively locate all the elements of a type.

Example

Note

To start, this example allocates an array of objects on the managed heap, and then assigns more derived types into each of the object reference elements. Next, the OfType extension method is invoked; please notice how it uses the 'string' type inside the angle brackets after the method call but before the parenthesis.

This syntax describes the OfType extension as a generic method. The resulting collection, then, of the OfType invocation is comprised of two string elements: the two strings found in the source array.

This C# program demonstrates the OfType extension method from System.Linq.

Program that uses OfType extension method [C#]

using System;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
	// Create an object array for the demonstration.
	object[] array = new object[4];
	array[0] = new StringBuilder();
	array[1] = "example";
	array[2] = new int[1];
	array[3] = "another";

	// Filter the objects by their type.
	// ... Only match strings.
	// ... Print those strings to the screen.
	var result = array.OfType<string>();
	foreach (var element in result)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

example
another

Windows Forms use

Question and answer

What is another, perhaps more practical, way of using the OfType extension in the C# language? One thing you can do is invoke OfType on the collection of Forms in a Windows Forms program; this enables you to locate declaratively all the form elements of a certain type, such as the Button or TextBox types. For a detailed look at this, please consult the specific article about searching Windows Forms programs.

Query Windows Forms Controls

Summary

The C# programming language

The OfType extension located in the System.Linq namespace in the C# language provides a useful way to query for elements of a certain type. As with other LINQ methods, it can be applied to various collection types. And while elaborate and custom type testing algorithms do have their place in some applications, the OfType method convincingly provides a declarative, query-oriented calling convention.

LINQ Examples
.NET