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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.