C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The OfType extension method is invoked. It uses the string type inside the angle brackets after the method call.
ExtensionResult: The collection has two string elements: the two strings found in the source array.
Generic Class, MethodC# program that uses OfType extension method
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);
}
}
}
Output
example
another
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.
PropertyC# program that uses OfType, inheritance
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);
}
}
}
Output
20
And: This enables you to locate declaratively all the form elements of a certain type, such as Button or TextBox.
Query Controls