Abdul Ahmad
Abdul Ahmad

Reputation: 10021

An object's child object is null when passed in argument

I have the following object structure:

class Facts {
 string name;
 string color;
 //other stuff
}
class Fruit {
  Facts Facts {get; set;}
}
class Apple : Fruit {
  Facts Facts {get; set;}
}
class Orange : Fruit {
  Facts Facts {get; set;}
}

Now, this is an ASP.NET MVC application, so I'm sending back an Apple object to my controller action method. In my action method, I'm calling a helper method and passing the Apple as an argument:

my helper method:

public void doSomething(Fruit fruit) {
  //do something with *fruit.Facts*
}

The problem is, my fruit object is being passed, but the Facts object inside is coming back as null. It's not null in the controller, but when I pass it to this helper method its null... and I don't understand why?

Does this have something to do with the controller passing objects to other methods as parameters or something? I know you can't pass a controller action method an object as a parameter in some instances. Is this related somehow?

Upvotes: 0

Views: 643

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502845

The problem is that you've got two entirely independent properties called Facts for an Apple. That's a really bad idea - it makes this sort of thing really confusing. The compiler is using whichever one it has access to, based on the compile-time type of the expression you're using.

You should already be getting a warning about this - don't ignore warnings! Here's a short but complete program demonstrating the problem:

using System;

class Fruit
{
    public string Name { get; set; }
}

class Apple : Fruit
{
    public string Name { get; set; }
}


class Test
{
    static void Main()
    {
        var apple = new Apple { Name = "AppleName" };
        Fruit fruit = apple;
        Console.WriteLine(fruit.Name); // Nothing!
        fruit.Name = "FruitName";
        Console.WriteLine(((Fruit) apple).Name); // FruitName
        Console.WriteLine(((Apple) fruit).Name); // AppleName
    }
}

One object, two names... depending on how you "view" the object.

Just get rid of the declarations of the Facts properties in Apple and Orange.

Upvotes: 3

Related Questions