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?
Therefore, there is an “is-a” relationship between the child and parent. Therefore, the child can be implicitly upcasted to the parent. However, a parent may or may not inherits the child's properties. However, we can forcefully cast a parent to a child which is known as downcasting.
Every child class has a parent class. Every instance of a child class has an instance of a parent class. A parent can be a child in another relationship.
The child class inherits the attributes and functions of its parent class. If we have several similar classes, we can define the common functionalities of them in one class and define child classes of this parent class and implement specific functionalities there.
It is because a true instance of Message is not a ChildMessage, whereas an instance of ChildMessage is a Message.
Unless myParentClass is actually instantiated with ChildMessage you cannot use the cast operator to force a forward cast as the actual underlying type is Message.
That said, there are implicit and explicit cast operators available for use on types, so you could perhaps create one that takes a Message and outputs a ChildMessage.
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 Message inside a ChildMessage:
class ChildMessage
{
private Message _innerMessage;
public ChildMessage(Message innerMessage)
{
_innerMessage = innerMessage;
}
}
You then expose either the Message or its properties through the ChildMessage class.
Second Option
This is just as feasible, inherit from the Message, but when you want to make a ChildMessage from a Message you will need to convert it, not cast it:
class ChildMessage : Message
{
public ChildMessage(Message m)
{
// Instantiate properties by copying from m
}
}
I think you somehow got it the wrong way - normaly you might want something like:
var myList =new List<Message> ();
var myChildObject = new ChildMessage();
myList.add(myChildObject)
myList[0] as ChildMessage == null // should not return null
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