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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With