Home
C#
OfType Examples
This page was last reviewed on Sep 8, 2022.
Dot Net Perls
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.
object Array
Note The OfType extension method is invoked. It uses the string type inside the angle brackets after the method call.
Extension
Result The collection has two string elements: the two strings found in the source array.
Generic
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
Inheritance. 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.
class
Part 1 We create a List of Animal instances, all of which are either instances of the Bird or Dog classes.
Part 2 We invoke OfType to get all the Dogs in the List. We then print a property of each returned instance.
Property
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
A discussion. 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.
And This enables you to locate declaratively all the form elements of a certain type, such as Button or TextBox.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 8, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.