OfType
This C# method searches for elements by their types. The System.Linq
namespace provides this generic method to test derived types.
By using this method, we get all the elements of a matching type. We do not need to cast the returned objects—we can use them directly.
To start, this example allocates an array of objects on the managed heap. It then assigns more derived types into each of the object reference elements.
OfType
extension method is invoked. It uses the string
type inside the angle brackets after the method call.string
elements: the two strings found in the source array.using System; using System.Linq; using System.Text; class Program { static void Main() { // Create an object array. 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); } } }example another
Consider this example: it has a base class
Animal, and then derives 2 classes from it—Bird and Dog. We then use OfType
to test the most derived types.
List
of Animal instances, all of which are either instances of the Bird or Dog classes.OfType
to get all the Dogs in the List
. We then print a property of each returned instance.using System; using System.Collections.Generic; using System.Linq; class Animal { } class Bird : Animal { } class Dog : Animal { public int Color { get; set; } } class Program { static void Main() { // Part 1: create List of Animal objects. var list = new List<Animal>(); list.Add(new Dog() { Color = 20 }); list.Add(new Bird()); // Part 2: use OfType to get all Dogs in the list. foreach (Dog value in list.OfType<Dog>()) { Console.WriteLine(value.Color); } } }20
What is another way of using the OfType
extension? One thing you can do is invoke OfType
on the collection of Forms in a Windows Forms program.
Button
or TextBox
.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.