Type Conversion - ToXxx Method or explicit?
In my recent work with LINQ to SQL I've had cause to convert between types quite a bit. Usually this involves taking a class that was generated from LINQ to SQL (mirroring the results of a stored procedure or the structure of a table) and converting it to one of our domain objects.
The way I've approached this to date is by implementing a custom "ToXxx" method in much the same way as the framework gives every object a "ToString" method. Here's an example:
internal Site ToSite() { return new Site { ID = SiteNumber, Code = SiteCode, Name = SiteName, FinancialCode = SiteFinCode, IsActive = SiteIsActive };
}
Pretty straight forward. My "Site" domain object closely matches the structure of the class that LINQ to SQL generated, so I just add this method to the LINQ class and call it when I need the conversion. Like this:
return (from ds in _dataContext.SiteRows select ds.ToSite()).ToList();
However: There's another way to do this. C# has a keyword called explicit, which you use to define a method that is called whenever someone tries to cast from one type to another. So my method could instead look like this:
public static explicit operator Site(SiteRow siteRow) { return new Site { ID = siteRow.SiteNumber, Code = siteRow.SiteCode, Name = siteRow.SiteName, FinancialCode = siteRow.SiteFinCode, IsActive = siteRow.SiteIsActive }; }
Which is better? I don't know for sure. Part of me wonders if it makes sense to return an entirely new object when all the calling code wants to do is cast. In that respect the ToSite() method kind of makes more sense. Also, a ToSite() method would allow you to specify parameters in the same way that ToString() can accept a format parameter. That's a benefit.
Anyway, the explicit (and implicit) operator is an interesting little animal, and one that deserves some attention if you're doing lots of type conversion.
# Trackback from Jason Haley on 20/12/2007 3:04 AM