C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
Also: You can cast anything to the base class object. This is because everything is derived from object.
Numeric CastsObject