C# Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object

StackOverflow https://stackoverflow.com/questions/15218175

Pergunta

Hello, I have a problem understanding why this piece of code:

using System;

class Person
{
    public Person()
    {
    }
}


class NameApp
{
    public static void Main()
    {
        Person me = new Person();
        Object you = new Object();

        me = you as Person;
        //me = (Person) you;

        System.Console.WriteLine("Type: {0}", me.GetType()); //This line throws exception
    }
}

Throws this exception:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at NameApp.Main() in C:\Users\Nenad\documents\visual studio 2010\Projects\Exercise 11.3\Exercise 11.3\Program.cs:line 21

Foi útil?

Solução 3

If you cast with the as keyword and the cast is not possible it returns null. Then in your case you call me.GetType() with me being null at the moment so an exception is thrown.

If you cast like (Person) objectOfTypeThatDoesNotExtendPerson an exception is thrown instantly at the cast.

Outras dicas

Your line

me = you as Person;

is failing and assigning null to me because you can't cast a base class type object to child class.

as (C# Reference)

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.

You probably want to cast person as object, since me is an Object, but you is not a person.

This code will always set me as null

   Object you = new Object();
   me = you as Person;

because Obejct is not person

but person is object :

object you = new Person();
me = you as Person;
Object you = new Object();
me = you as Person;

you is an object, not a Person so you as Person will simply return null.

me = you as Person;

me is null if you cannot be casted to Person (and that's what happening in your situation, because new Object() cannot be casted to Person.

The as operator returns null if the object was not of the type you requested.

me = you as Person;

you is an Object, not a Person, so (you as Person) is null and therefore me is null. When you call GetType() on me afterwards, you get a NullReferenceException.

public static void Main()
{
    Person me = new Person();
    Object you = new Object();

    // you as person = null
    me = you as Person;
    //me = (Person) you;

    System.Console.WriteLine("Type: {0}", me.GetType()); //This line throws exception
}

Object can not be cast to a Person. It is a princip of object oriented programming.

Object is a parent class of a Person. Every class inherits it,

you can cast Person to Object, but cannot cast Object to Person

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top