In C#, I have a class A that I cannot modify. From this class I've created class B (i.e. inherited from A) which adds some properties. I also have a static function that returns List<A>
when GetListOfA() is called.
How can I cast the return from GetListOfA() to List<B>
?
e.g. List<B>
bList = foo.GetListOfA() as List<B>
This article describes a simple approach to downcasting in C#; downcasting merely refers to the process of casting an object of a base class type to a derived class type. Upcasting is legal in C# as the process there is to convert an object of a derived class type into an object of its base class type.
In C# upcasting is implicit so we can convert an object's reference to its base class reference. Wherever a method requires an object of a given type, you can pass an object of that type or of any of the types that derive from that type.
Why Down-Casting is required in C# programming? It is possible that derived class has some specialized method. For example, in above derived class Circle, FillCircle() method is specialized and only available to Circle class not in Shape base class.
If you're using C# 3.0 (Visual Studio 2008), you can:
using System.Linq;
List<B> bList = foo.GetListOfA().Cast<B>().ToList();
Using System.Linq, you can say
List<B> bList = foo.GetListOfA().Cast<B>().ToList()
Or
var bs = foo.GetListOfA().Cast<B>()
Or
static class AExts
{
public List<B> AsB( this List<A> list )
{
return list.Cast<B>().ToList();
}
}
List<B> bList = foo.GetListOfA().AsB();
Or
static class FooExts
{
public List<B> AsB( this Foo foo )
{
return list.GetListOfA().AsB();
}
}
List<B> bList = foo.AsB();
Or if you dont have/ cant /wont use Linq, algorithms in PowerCollections has the same thing
And I didnt look at the other answer even though it probably says the same!
You can't. You must actually create a new List<B>
and add all the items from the original list to the new list.
The easiest way to do this, apart from writing your own method to do so, is to use Linq (see other answers).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With