Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upcast a collection of base class in C#?

Tags:

c#

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>

like image 883
Guy Avatar asked Aug 11 '09 23:08

Guy


People also ask

Is Downcasting possible in C#?

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.

What is the use of Upcasting in C#?

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 do we use Upcasting and Downcasting in C#?

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.


3 Answers

If you're using C# 3.0 (Visual Studio 2008), you can:

using System.Linq;

List<B> bList = foo.GetListOfA().Cast<B>().ToList();
like image 144
Ben M Avatar answered Nov 11 '22 01:11

Ben M


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!

like image 37
Ruben Bartelink Avatar answered Nov 11 '22 00:11

Ruben Bartelink


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

like image 44
John Calsbeek Avatar answered Nov 11 '22 00:11

John Calsbeek