Calling child constructor by casting (ChildClass)parentObject; to track revisions

Posted by FreshCode on Stack Overflow See other posts from Stack Overflow or by FreshCode
Published on 2010-04-23T11:14:15Z Indexed on 2010/04/23 11:23 UTC
Read the original article Hit count: 124

To track revisions of a Page class, I have a PageRevision class which inherits from Page and adds a revision ID (Guid RevisionID;).

If possible, how should I cast an existing Page object to a PageRevision and ensure that the PageRevision constructor is called to create a new revision ID?

I could could have a PageRevision(Page page) constructor which generates the Guid and copies all the Page attributes, but I want to automate it, especially if a Page class has many attributes (and I later add one, and forget to modify the copy constructor).

Desired use

Page page = new Page(123, "Page Title", "Page Body"); // where 123 is page ID
PageRevision revision = (PageRevision)page;
// now revision.RevisionID should be a new Guid.

Page, PageRevision classes:

public class Page
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
}

public class PageRevision : Page
{
    public Guid RevisionID { get; set; }

    public PageRevision()
    {
        this.RevisionID = Guid.NewGuid();
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about inheritance