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