
You want to cast all the elements in a sequence to another type in your C# program. For example, if you have a collection of objects, you can cast these to a base class. The Cast extension method, found in System.Linq, is ideal for this purpose.
This program introduces the A class and the B class. The B class derives from the A class. In the Main entry point, we create an array of B object instances. Next, we use the Cast extension method with type parameter A. This means that each B object will be cast to its base class A.
This C# example demonstrates the Cast extension method from System.Linq.
Program that uses Cast<A> [C#]
using System;
using System.Linq;
class A
{
public void Y()
{
Console.WriteLine("A.Y");
}
}
class B : A
{
}
class Program
{
static void Main()
{
B[] values = new B[3];
values[0] = new B();
values[1] = new B();
values[2] = new B();
// Cast all objects to a base type.
var result = values.Cast<A>();
foreach (A value in result)
{
value.Y();
}
}
}
Output
A.Y
A.Y
A.YResult. The final result of the program is that you have an IEnumerable collection of A instances. These are actually still B instances as well, but are now referenced through their base type. We call the Y() method to demonstrate that they are real A objects.

The Cast extension method is not terribly useful for casting numeric types. For example, you cannot cast a double to an int without an exception. Implicit conversions are allowed, however. For example, you can cast an int to a uint. You can cast anything to the base class object.
Numeric Casts Object TypeThe Cast extension method is of limited utility in most programs. However, if you need to cast a collection in a single statement, this is the best way to do it. Check out the other LINQ articles on this site for more neat declarative programming techniques.
LINQ Examples