Cast. The Cast method casts every element. It is an extension in the System.Linq namespace. It casts each element to the specified type. And the result is a collection of the desired type.
Numeric. Cast() 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.
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.
Detail We have an IEnumerable of "A" instances. These are still "B" instances as well, but are now referenced through their base type.
And We call the Y() method to show that they are real "A" objects. The Y() method is only available on an "A" instance.
Tip You can cast anything to the base class object. This is because everything is derived from object.
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();
}
}
}A.Y
A.Y
A.Y
A short 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.
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 25, 2022 (edit).