TheDeveloperBlog.com


C# Cast Extension: System.Linq

Cast. The Cast method casts every element. It is an extension method in the System.Linq namespace. It casts each element to the specified type. And the result is a collection of the desired type.


Example. First, this program introduces the A class and the B class. The two are connected—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.

C# program that uses Cast

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.Y

In this program, we 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.


Numeric. The Cast extension method is less useful for casting numeric types. You cannot cast a double to an int without an exception. But implicit conversions are allowed. For example, you can cast an int to a uint.

Also: You can cast anything to the base class object. This is because everything is derived from object.

Numeric CastsObject Type

Summary. The Cast extension method is of limited utility in most programs. But if you need to cast a collection in a single statement, this is the best way to do it. Other LINQ articles on this site also show declarative programming techniques.