Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and inheritance. Base class property is null when the object is Extended class object

Tags:

c#

inheritance

I have the following classes:

public class BaseContainer
{
   public BaseItem item {get; set;}
}

public class ExtendedContainer : BaseContainer
{
   new public ExtendedItem item {get; set;}
}

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

public class ExtendedItem : BaseItem
{
   public string Surname { get; set; }
}

Then I have the following instructions:

ExtendedItem ei = new ExtendedItem { Name = "MyName", Surname = "MySurname" };
ExtendedContainer ec = new ExtendedContainer { item = ei };
BaseContainer bc = ec;
string temp = bc.item.Name;  // bc.item is null, why?

Why bc.item is null? It shouldn´t because ExtendedItem is a subclass if BaseItem, but when I run the code it is null. Can anyone help me with this issue?

The reason I´m doing this is that I´m using MVC3 and I´m passing to partial views objects/models that are part of a similar structure, and I normally just need the properties in the base class.

Thanks in advance.

UPDATE

Jon is right, I´m accessing different objects. What I did to fix it is to use constructors to set the item properties to the same object. Like this:

public class BaseContainer
{
    public BaseItem item {get; set;}
    public BaseContainer(BaseItem item)
    {
        this.item = item;
    }
}

public class ExtendedContainer : BaseContainer
{
    public ExtendedItem item {get; set;}

    public ExtendedContainer(ExtendedItem item) : base(item)
    {
        this.item = item;
    }
}

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

public class ExtendedItem : BaseItem
{
    public string Surname { get; set; }
}

And then I just create the object:

    ExtendedItem ei = new ExtendedItem { Name = "MyName", Surname = "MySurname" };
    ExtendedContainer ec = new ExtendedContainer(ei);
    BaseContainer bc = ec;
    string temp = bc.item.Name;

it works now

like image 479
Alfonso Muñoz Avatar asked Jun 05 '12 15:06

Alfonso Muñoz


1 Answers

You've got two entirely separate properties here, which can store different values.

You've set the ExtendedContainer.item property on the object, but you haven't set the BaseContainer.item property.

Imagine the two properties had entirely different names - you wouldn't expect setting one to change the other then, would you? Well as far as the CLR is concerned, the fact that the two properties have the name is merely a coincidence.

like image 106
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet