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