I have two classes, named Post and Question. Question is defined as:
public class Question : Post
{
//...
}
My Question class does not override any members of Post, it just expresses a few other ones.
What I want to accomplish
I have an object of type Post, whose members are populated. Now, I want to convert it into a Question, so that I can add values for those few other members.
This is my current code, using an explicit cast conversion:
Post postToQuestion = new Post();
//Populate the Post...
Question ques = (Question)postToQuestion; //--> this is the error!
//Fill the other parts of the Question.
Problem
I am getting an InvalidCastException. What am I doing wrong?
The problem is that you can’t cast from parent to child. You can create a constructor for the child class that takes the parent class as a param:
Question ques = new Question(myPost);
You could also use the implicit operator to make it simple to do this:
Question ques = myPost;
http://www.codeproject.com/KB/cs/Csharp_implicit_operator.aspx
EDIT:
Actually, I just tried typing up a demo for you doing the implicit operator:
but aparently C# doesn’t let you do implicit conversions with a base class.