I am extending the existing .NET framework class by deriving it. How do I convert an object of base type to derived type?
public class Results { //Framework methods }
public class MyResults : Results { //Nothing here }
//I call the framework method
public static MyResults GetResults()
{
Results results = new Results();
//Results results = new MyResults(); //tried this as well.
results = CallFrameworkMethod();
return (MyResults)results; //Throws runtime exception
}
I understand that this happens as I am trying to cast a base type to a derived type and if derived type has additional properties, then the memory is not allocated. When I do add the additional properties, I don't care if they are initialized to null.
How do I do this without doing a manual copy?
You can't. If results
doesn't refer to a MyResults
(e.g. if CallFrameworkMethod
returns a base Results
instance), then casting won't make it so: you'll need to create a new MyResults
, based on the existing non-MyResults
. Casting is about changing the compile-time type of the reference, not about changing the concrete type of the referenced object.
You can use tools such as Reflection or AutoMapper to help with the initialisation of the new MyResults
object -- but a new MyResults
object there must be, because you cannot tell a base Results
object to become a MyResults
object.
How about:
...
MyResults results = new MyResults();
...
And you maybe also need to create a COnstructor in your MyResults
class:
public class MyResults : Results
{
public MyResults() : base() {}
}
What exactly means "nothing here"?
EDIT
results = (CallFrameworkMethod() as MyResults);
It doesnt throw the exception, but if it would be useful for you - it depends on what you would like to do further...
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