C# Cast Extension: System.Linq

Use the Cast extension method from System.Linq to change the type of elements.

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

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.

Example: 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.

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

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

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
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to