Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of Base Class array to Derived Class array

Is it possible in C# to explicitly convert a base class object array to one of it's derived class object array? I have class C derived from class A and I'm trying to convert the base class object array to the derived class object array but it returns returns a null value.

public interface I
{
   public string Name;
   public string Id;
}
public class A
    {
        public string name;
        public string id;
    }

public class B: A,I
{
    public string Name
    {
       get { return name; }
       set{name= value;}
    }

    public string Id
    {
       get { return id; }
       set{id= value;}
    }
}


 A[] baseClassList= GetValues();
 B[] derivedClassList= baseClassList as B[];---THIS IS RETURNING NULL

How can i solve this? Any help is appreciated.

like image 471
merazuu Avatar asked Dec 16 '22 00:12

merazuu


2 Answers

You can create a B[] from baseClassList using Linq pretty easily but it won't be as simple as a cast.

B[] derivedClassList = baseClassList.OfType<B>().ToArray();

EDIT: Alternatively - if you want to convert the contents of the array I'd recommend a copy-constructor.

public B(A source)
{
    Name = source.name;
    Id = source.id;
}

Then you can convert like so:

B[] derivedClassList = baseClassList.Select(e => e is B ? (B)e : new B(e)).ToArray();
like image 166
McAden Avatar answered Feb 12 '23 23:02

McAden


Why not just do this?

Assuming that your baseClassList collection of objects of A type are all really objects of B type underneath.

B[] derivedClassList = baseClassList.Cast<B>().ToArray();
like image 20
Derek W Avatar answered Feb 13 '23 00:02

Derek W