0

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?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263

3 Answers3

5

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?

Tarec
  • 3,268
  • 4
  • 30
  • 47
3

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.      
}
Tigran
  • 61,654
  • 8
  • 86
  • 123
0

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.

marce
  • 106
  • 1