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


i have 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 have 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 null, why? 

why bc.item null? shouldn´t because extendeditem subclass if baseitem, when run code null. can me issue?

the reason i´m doing i´m using mvc3 , i´m passing partial views objects/models part of similar structure, , need properties in base class.

thanks in advance.

update

jon right, i´m accessing different objects. did fix use constructors set item properties same object. 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 create 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 2 entirely separate properties here, can store different values.

you've set extendedcontainer.item property on object, haven't set basecontainer.item property.

imagine 2 properties had entirely different names - wouldn't expect setting 1 change other then, you? far clr concerned, fact 2 properties have name merely coincidence.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -