Click here to Skip to main content
Click here to Skip to main content

Forgotten C# language features: implicit operator

By , 26 Feb 2013
 

Introduction

Sometimes we get so wrapped up in using the latest and greatest language features that we forget how to use those tools that have been available since .NET 1.1. Let's take a quick look back at the implicit operator keywords.

Background 

I was writing some code the other day, and found that I needed a conversion function to convert one class to another. My initial, .NET 3.5 inspired, idea was to write a simple extension method in a static Converters class.

For this article, I will demonstrate converting a storefront's Order object into a Receipt object, suitable for formatting and transmission to a customer. My initial code looked similar to the following:

public static class Converters {
     
    public static Receipt AsReceipt(this Order myOrder) {
 
        return new Receipt {
            // set properties in the Receipt from the Order object
        };
 
    }
} 

I would use this static extension method in a form that looks similar to some extension methods you've seen in LINQ operations:

Receipt thisReceipt = myOrder.AsReceipt(); 

Using the Code 

There is a little referenced C# language feature that has been around since .NET 1.1 called the implicit operator keywords. These keywords allow us to encapsulate the conversion to and from a user-defined class with a static method inside that class. These keywords should be used when you can guarantee that the developer consuming this method will not lose data, nor will an exception ever be thrown. If either of these criteria cannot be met, then it is recommended that you use the explicit keyword (discussed below).

Here you can find the documentation on MSDN for the implicit operator language feature.

I moved my code from the static Converters class into the Receipt class and used these keywords as follows:

public class Receipt {

  // Other properties and methods

  public static implicit operator Receipt(Order myOrder) {
    // Convert FROM an Order INTO a Receipt
    
    return new Receipt {
      // set the properties in the Receipt from the Order object
    };
   
  }
}

Now, I can rewrite my usage of the conversion function as:

Receipt thisReceipt = myOrder; 

The code is now much easier to understand. There are no extra interfaces being added to facilitate this conversion. Additionally, I don't have an extra 'utility' class for these conversion operations. The conversion concerns for a class are kept within the class to which they apply. 

Points of Interest 

If you would prefer your code to be a bit more declarative in the conversion process, there is a similar explicit operator keyword. This keyword should be used in place of the implicit operator if the developer is not guaranteed a conversion without exception or if data loss will occur. This operator  allows the conversion function to be used in this format: 

Receipt thisReceipt = (Receipt)myOrder;  

We still maintain a very simple syntax that is descriptive of the code operation desired. 

Conclusion

These operator keywords are a powerful tool, one that many of us don’t know about or we forget that they are available to us. Let’s try to make better use of these native language features, as they will help us improve our class design by keeping all of our object’s conversion concerns in one location.

History    

  • v3 - Included notes about exception handling in the "implicit operator" function 
  • v2 - Replaced var keyword with explicit typing 
  • v1 - Initial publication - Sept 3, 2012 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jeffrey T. Fritz
Telerik
United States United States
An ASP.NET Developer Evangelist. Jeffrey is a software developer coach, architect, and speaker in the Microsoft.Net community. A frequent INETA contributor and a member of the AspInsiders group, Jeffrey makes regular appearances at conferences and user group meetings in an effort to grow the next generation of software developers
Follow on   Twitter   Google+

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberDave Boross13-Mar-13 6:42 
GeneralReplymemberChampion·Chen27-Feb-13 13:56 
GeneralMy vote of 5memberPaul A Francis26-Feb-13 21:51 
GeneralGreat tipmemberStephen Inglish26-Feb-13 8:40 
GeneralMy vote of 5memberZuoliu Ding4-Sep-12 8:54 
GeneralMy vote of 5memberVitaly Tomilov4-Sep-12 3:41 
Generalimplicit operator opens the box of the pandora...memberAndreas Gieriet3-Sep-12 10:50 
GeneralRe: implicit operator opens the box of the pandora...memberJeffrey T. Fritz3-Sep-12 11:11 
GeneralRe: implicit operator opens the box of the pandora...memberAndreas Gieriet3-Sep-12 11:27 
GeneralThoughtsmemberPIEBALDconsult3-Sep-12 8:43 
GeneralRe: ThoughtsmemberJeffrey T. Fritz3-Sep-12 8:48 
GeneralMy vote of 5mvpOriginalGriff3-Sep-12 8:35 
GeneralMy vote of 5mvpMika Wendelius3-Sep-12 7:41 
GeneralMy vote of 3memberEd Nutting3-Sep-12 7:14 
GeneralRe: My vote of 3memberJeffrey T. Fritz3-Sep-12 7:21 
GeneralRe: My vote of 3memberEd Nutting3-Sep-12 7:39 
GeneralRe: My vote of 3 [modified]memberAndreas Gieriet4-Sep-12 0:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130617.1 | Last Updated 26 Feb 2013
Article Copyright 2012 by Jeffrey T. Fritz
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid