-2

I have a three classes: Entity, Student and Teacher. All objects are saved in Entity array. I need to verify class of Entity[i] item but when I try to virify I recieve an warning. Program is stopped and nothing goes. What to do?

class Entity {
     string param0;
}

class Student : Entity {
    string param1;
    //consturctor...
}

class Teacher : Entity {
    class string param2;
    //consturctor...
}

Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");
...
...
var es = entities[i] as Student; 
if (es.param1 != null) //here throw nullReferenceException
   Debug.Log(es.param1); 
else
   Debug.log(es.param2);

What i do incorect? How i can verify object class correctly?

Willem Van Onsem
  • 321,217
  • 26
  • 295
  • 405
Artiom
  • 133
  • 6
  • 1
    But `i` is never defined... Please provide a *minimum working example* (something that compiles). – Willem Van Onsem Jun 09 '15 at 01:46
  • "The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception" - https://msdn.microsoft.com/en-us/library/cscsdfbt.aspx – vesan Jun 09 '15 at 01:51
  • `es.param1` should be `es` in the if statement – SimpleVar Jun 09 '15 at 02:04

1 Answers1

4

Your issue is that you are setting up your array with different types of Entity:

Entity[] entities = new Entity[5];
entities[0] = new Student("some string1");
entities[1] = new Teacher("some string2");

When you try to cast the entity at position 1 (i.e. the second item in the array) as a Student, the result will be null, as the entity is a Teacher:

var es = entities[i] as Student; 

es is null at this point.

Instead, check the type, and then access the specific parameter once you know what type of entity you have. One way to do this would be:

if (es is Student)
{
   Debug.Log((es as Student).param1); 
}
else if (es is Teacher)
{
   Debug.log((es as Teacher).param2);
}
else
{
    //some other entity
}
Brendan Green
  • 10,893
  • 5
  • 40
  • 68