Convert/Cast base type to Derived type

Posted by user102533 on Stack Overflow See other posts from Stack Overflow or by user102533
Published on 2010-03-25T21:24:23Z Indexed on 2010/03/25 21:33 UTC
Read the original article Hit count: 433

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET