Casting an Object is making it become null

In a call back like this:

 this.Model.LoadStudent(student_key, (o, a) =>
                            {
                                var student = o as Students;

If I put a break point on first line, debugger shows me that "o" has what I am looking for and also shows me its type which is "Students" but as soon as it goes to next line and does the cast, the result is null. Why? What is happening?

Jon Skeet
people
quotationmark

You're not casting - you're using the as operator. If you instead actually cast, I suspect you'll get an exception:

var student = (Students) o;

I suspect you've actually got multiple types called Students, and if you really cast instead of using as you'll see the actual type involved.

For example:

using System;

namespace Bad
{
    class Students {}

    class Test
    {
        static void Main()
        {
            object o = new Good.Students();
            Students cast = (Students) o;
        }
    }
}

namespace Good
{
    class Students {}
}

This leads to:

Unhandled Exception: System.InvalidCastException:
    Unable to cast object of type 'Good.Students' to type 'Bad.Students'.
   at Bad.Test.Main()

Note how you get the fully-qualified type names in the exception.

In general, it's a bad idea to use as unless you really expect that the object may not be of the right type, and usually you check for that afterwards. See my blog post on the topic for more details.

people

See more on this question at Stackoverflow