Reputation: 7444
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
Upvotes: 1
Views: 9836
Reputation: 1433
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.
Upvotes: 1
Reputation: 2148
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
Upvotes: 1
Reputation: 526
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
}
Upvotes: 1
Reputation: 77364
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.
Upvotes: 1
Reputation: 125650
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
.
Upvotes: 1
Reputation: 1039498
Object you = new Object();
me = you as Person;
you
is an object, not a Person so you as Person
will simply return null.
Upvotes: 1
Reputation: 11287
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;
Upvotes: 2
Reputation: 223412
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.
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.
Upvotes: 2