Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

Forgotten C# language features: implicit operator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (15 votes)
26 Feb 2013CPOL2 min read 42K   24   17
A throw-back to a .NET 1.1 feature to use instead of writing an extension method.

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:

C#
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:

C#
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:

C#
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:

C#
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: 

C#
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)


Written By
Program Manager
United States United States
Jeff Fritz is a senior program manager in Microsoft’s Developer Division working on the .NET Community Team. As a long time web developer and application architect with experience in large and small applications across a variety of verticals, he knows how to build for performance and practicality. Four days a week, you can catch Jeff hosting a live video stream called 'Fritz and Friends' at twitch.tv/csharpfritz. You can also learn from Jeff on WintellectNow and Pluralsight, follow him on twitter @csharpfritz, and read his blog at jeffreyfritz.com

Comments and Discussions

 
GeneralMy vote of 5 Pin
Dave Boross13-Mar-13 6:42
Dave Boross13-Mar-13 6:42 
GeneralReply Pin
Champion Chen27-Feb-13 13:56
Champion Chen27-Feb-13 13:56 
GeneralMy vote of 5 Pin
Paul A Francis26-Feb-13 21:51
Paul A Francis26-Feb-13 21:51 
Clear, concise and interesting. I'm not sure how keen I am on implicit conversions for objects that are not clear equivalents though.
GeneralGreat tip Pin
Stephen Inglish26-Feb-13 8:40
Stephen Inglish26-Feb-13 8:40 
GeneralMy vote of 5 Pin
Zuoliu Ding4-Sep-12 8:54
Zuoliu Ding4-Sep-12 8:54 
GeneralMy vote of 5 Pin
Vitaly Tomilov4-Sep-12 3:41
Vitaly Tomilov4-Sep-12 3:41 
Generalimplicit operator opens the box of the pandora... Pin
Andreas Gieriet3-Sep-12 10:50
professionalAndreas Gieriet3-Sep-12 10:50 
GeneralRe: implicit operator opens the box of the pandora... Pin
Jeffrey T. Fritz3-Sep-12 11:11
sponsorJeffrey T. Fritz3-Sep-12 11:11 
GeneralRe: implicit operator opens the box of the pandora... Pin
Andreas Gieriet3-Sep-12 11:27
professionalAndreas Gieriet3-Sep-12 11:27 
GeneralThoughts Pin
PIEBALDconsult3-Sep-12 8:43
mvePIEBALDconsult3-Sep-12 8:43 
GeneralRe: Thoughts Pin
Jeffrey T. Fritz3-Sep-12 8:48
sponsorJeffrey T. Fritz3-Sep-12 8:48 
GeneralMy vote of 5 Pin
OriginalGriff3-Sep-12 8:35
mveOriginalGriff3-Sep-12 8:35 
GeneralMy vote of 5 Pin
Wendelius3-Sep-12 7:41
mentorWendelius3-Sep-12 7:41 
GeneralMy vote of 3 Pin
Ed Nutting3-Sep-12 7:14
Ed Nutting3-Sep-12 7:14 
GeneralRe: My vote of 3 Pin
Jeffrey T. Fritz3-Sep-12 7:21
sponsorJeffrey T. Fritz3-Sep-12 7:21 
GeneralRe: My vote of 3 Pin
Ed Nutting3-Sep-12 7:39
Ed Nutting3-Sep-12 7:39 
GeneralRe: My vote of 3 Pin
Andreas Gieriet4-Sep-12 0:03
professionalAndreas Gieriet4-Sep-12 0:03 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.