The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

Friday, August 14, 2009 #

Seeing as I have to search for this code snippet on most occasions that I use it, I’ve decided to put it here as a post. I often find that I have to repeat the same code over and over when converting between two similar types (e.g. Person domain object and PersonDto object). If you see something like this crop up too often:

var personDto =  new PersonDto
{
    Id = person.Id,
    FirstName = person.FirstName,
    LastName = person.LastName,
    Age = person.Age
};

You have two options: 1) Refactor your code into an extension method so you have something like this:

var personDto = person.ConvertToPersonDto();

or, refactor you code into an implicit operator overload, so that your code looks like this:

var personDto = (PersonDto) person;

I prefer the latter, primarily because my refactored code can be part of the same class, and not have to be placed in separate static classes, as with all extension methods. The overloading of the operator looks like this:

public static implicit operator PersonDto (Person person)
{
    return new PersonDto
               {
                   Id = person.Id,
                   FirstName = person.FirstName,
                   LastName = person.LastName,
                   Age = person.Age
               };
}