views:

194

answers:

4

So basically I have this

public class Ticket{
    public TicketNumber {get; set;}
    ..a bunch more properties...
}

I want to add some properties using a subclass like this using subsumption instead of composition.

public class TicketViewModel(Ticket ticket){
    //set each property from value of Ticket passed in
    this.TicketNumber = ticket.TicketNumber;
    ...a bunch more lines of code..

    //additional VM properties
    public SelectList TicketTypes {get; private set;}
}

How do I instantiate the properties without having to write all the lines like this

this.TicketNumber = ticket.TicketNumber;

Is there some kind of shortcut? Something like in the subclass constructor?

this = ticket; 

Obviously this doesn't work but is their some way so I don't have to modify my subclass if addng/removing a property to the parent class? Or something?

A: 

Sorry, there's no shortcut.

I frequently wish there were. I started programming with COBOL ages ago, and it had a MOVE CORRESPONDING statement for moving the same-named members from one record to another. I've wished for that in every language I've used since then.

John Saunders
Couldn't it be done with reflection? I don't use the Type object enough to mock up working code right now, but if you just matched up property names and types, I'd imagine you can do something like this. I wouldn't actually go through with it, though. Ew.
Stuart Branham
+3  A: 

Have a look at Automapper

Noel Kennedy
+1: Ta!... I was working on my own object-mapper. Didn't know someone else already made one... :D! Cool!
Simon
A: 

You can mark the copy-able properties with an attribute and reflectively attempt to assign them. It's not the best way to go about it.

Aren
+1  A: 

You can create a constructor on your base class and then call that from the inheritor, like this:

public class Ticket{
    public string TicketNumber {get; set;}
    ..a bunch more properties...

    public Ticket (string ticketNumber, a bunch more values) {
         this.TicketNumber = ticketNumber;
         // a bunch more setters
    }
}

Then in your inheriting class simply do:

public class TicketViewModel : Ticket {
     public string SomeOtherProperty { get; set; }

     public TicketViewModel(string ticketNumber, ..., string someOtherProperty)
          : base(ticketNumber, ....) 
     {
          this.SomeOtherProperty = someOtherProperty;
     }
}
Thomas