I have Message class which I have extended and added new property.
class ChildMessage: Message
{
prop...
}
While trying to add Message Class to ChildMessage list I get Null reference for added class.
var myChildList =new List<ChildMessage> ();
var myParentClass = new Message();
myChildList.add(myParentClass as ChildMessage)
myChildList[0] == null //Always return null
What is wrong with my code? What are the alternatives?
It is because a true instance of
Messageis not aChildMessage, whereas an instance ofChildMessageis aMessage.Unless
myParentClassis actually instantiated withChildMessageyou cannot use the cast operator to force a forward cast as the actual underlying type isMessage.That said, there are
implicitandexplicitcast operators available for use on types, so you could perhaps create one that takes aMessageand outputs aChildMessage.http://msdn.microsoft.com/en-us/library/85w54y0a.aspx
Knowing that you are given these types and you have no choice but to use them, you have two options in order to extend that type.
First Option
Use the decorator/wrapper pattern to wrap a
Messageinside aChildMessage:You then expose either the
Messageor its properties through theChildMessageclass.Second Option
This is just as feasible, inherit from the
Message, but when you want to make aChildMessagefrom aMessageyou will need to convert it, not cast it: