Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert/Cast base type to Derived type

Tags:

c#

.net

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?

like image 626
Nick Avatar asked Mar 25 '10 21:03

Nick


2 Answers

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.

like image 106
itowlson Avatar answered Oct 21 '22 08:10

itowlson


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...

like image 1
Gacek Avatar answered Oct 21 '22 06:10

Gacek