Reputation: 16310
I have the following code:
public class BaseClass {}
public class Class1 : BaseClass {}
public class Class2 : BaseClass {}
public class BaseClassList : List<BaseClass> {}
public class Class1List : List<Class1> {}
public class Class2List : List<Class2> {}
public void Setup()
{
BaseClassList b = new BaseClassList();
b.Add(new BaseClass());
b.Add(new BaseClass());
b.Add(new BaseClass());
var list = from a in b
select a;
Class1List c1 = new Class1List();
foreach (BaseClass a in b)
{
var o = a as Class1;
if (o != null)
c1.Add(o);
}
}
However, when casting a as Class1, o is always null. What is the problem?
Upvotes: 0
Views: 124
Reputation: 106
Because you're casting your base class to a super class. It's like telling the compiler that a "Person" is always "Software Developer", it should be the other way around. So, a "Software Developer" is always a "Person" and an "Accountant" is also a "Person."
Thus, "BaseClass" is to "Person"; "Class1" is to "Software Developer"; "Class2" is to "Accountant"
So you should add an instance of either a "Software Developer/Class1" or "Accountant/Class2" to the list of "Person" which is the BaseClassList.
Then mark you BassClass as abstract.
Upvotes: 0
Reputation: 62256
becasue a
is a BaseClass
according to your code:
...
b.Add(new BaseClass());
b.Add(new BaseClass());
b.Add(new BaseClass());
...
and you can not cast base class to child class, you have to do it vice versa.
Example:
...
b.Add(new Class1());
b.Add(new Class1());
...
and after this will be correct:
foreach (var a in b)
{
var o = a as Class1;//CORRECT.
}
Upvotes: 3
Reputation: 3255
The problem is that a
is not Class1
object. That's all.
Read your code carefully again - why would you think a BaseClass
object can be casted to a class, that derives from it?
Upvotes: 5