C# OfType Example, Get Elements of Matching TypeThis C# program demonstrates the OfType extension method from System.Linq.
searches for elements by their types. The System.Linq namespace provides this generic method to test derived types. By using the OfType method, we get all the elements of a matching type.LINQ
this example allocates an array of objects on the managed heap. It then assigns more derived types into each of the object reference elements. Next the OfType extension method is invoked.Object ArrayExtension
Note: It uses the string type inside the angle brackets after the method call but before the parenthesis.
Result: The collection has two string elements: the two strings found in the source array.Generic Class, Method
C# program that uses OfType extension method
static void Main()
// Create an object array for the demonstration.
object array = new object;
array = new StringBuilder();
array = "example";
array = new int;
array = "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)
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.
And: This enables you to locate declaratively all the form elements of a certain type, such as Button or TextBox.ButtonTextBox
Tip: For a detailed look at this, please consult the specific article about searching Windows Forms programs.Query Windows Forms
The OfType extension is located in the System.Linq namespace in the C# language. It 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.
So: Custom type testing algorithms have their place. But OfType provides a simple, query-oriented calling convention.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.