I recently had a friend ask me about my use of implicit operators. I’ve been using them for a while now, but don’t think they’ve gained much traction for some reason, as I rarely come across code where they’ve been implemented.
Using implicit or explicit operators at their base implementation is quite easy, there’s a few simple rules to follow when implementing them:
- The operator must be enclosed in the class or partial class that it converts
- It must accept only 1 parameter
There’s a few other rules, but those are the two important ones to follow when getting started.
Pretty easy to implement, and you implement explicit operators the same way. The major difference being the required explicit call on an explicit operator such as:
For this example, I’ve created a very small model of a customer object, with addresses. This model is not connected to a database, and utilizes the model designer of the Entity Framework 4.0.
I’ve also wired up to POCO (Plain old CLR Objects) objects, as DTO’s (data transfer objects). The scope of this entry is not to describe why you’d use POCO or transfer objects, but if you’re using them, and doing manual conversions this will save you a LOT of headache. :)
Once we have our model in place, and our POCO objects created, we can get into the meat of the operators we want to implement.
Lets start with the CustomerDTO operator:
You’ll notice that when you implement this code, you receive this error:
This is exactaly where implicit operators come in! When we go and define the implicit operator for the Address, we’ll solve our problem here:
The finished CustomerDTO implicit operator:
Now all that would be left, would be to extend the partial classes of our Entity Framework objects, such as the Customer and Address to return DTO objects
Now, anywhere in our business logic we can use implicit converstion such as
AddressDTO = Address
Address = AddressDTO
Customer = CustomerDTO
CustomerDTO = Customer
Hope that makes life easier ---