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

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
               };
}
posted on Friday, August 14, 2009 10:08 AM

Feedback

# re: Overloading the implicit operator for casting 8/15/2009 5:51 AM Matt
Hmm, I'd never thought about using implicit casting for this, neat! I typically put a constructor on my DTO (or in the case of ASP.NET MVC, my view model) that takes the domain object as a parameter, then pulls out what it wants. I usually use AutoMapper to do the simple mappings, then add custom logic when a complex mapping scenario calls for it.

Comments have been closed on this topic.