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

Tagged as

Forgotten C# language features: implicit operator

, 26 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

Jeffrey T. Fritz
Telerik
United States United States
A Microsoft MVP, ASPInsider and ASP.NET Developer Evangelist for Telerik. Jeffrey is a software developer coach, architect, and speaker in the Microsoft.Net community. A Pluralsight author and international speaker, Jeffrey makes regular appearances at conferences such as TechEd, DevIntersection, CodeStock, FalafelCon, DevReach and New York Code Camp as well as user group meetings in an effort to grow the next generation of software developers
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 5 PinmemberDave Boross13-Mar-13 7:42 
GeneralReply PinmemberChampion·Chen27-Feb-13 14:56 
GeneralMy vote of 5 PinmemberPaul A Francis26-Feb-13 22:51 
GeneralGreat tip PinmemberStephen Inglish26-Feb-13 9:40 
GeneralMy vote of 5 PinmemberZuoliu Ding4-Sep-12 9:54 
GeneralMy vote of 5 PinmemberVitaly Tomilov4-Sep-12 4:41 
Generalimplicit operator opens the box of the pandora... PinmemberAndreas Gieriet3-Sep-12 11:50 
GeneralRe: implicit operator opens the box of the pandora... PinmemberJeffrey T. Fritz3-Sep-12 12:11 
GeneralRe: implicit operator opens the box of the pandora... PinmemberAndreas Gieriet3-Sep-12 12:27 
GeneralThoughts PinmemberPIEBALDconsult3-Sep-12 9:43 
GeneralRe: Thoughts PinmemberJeffrey T. Fritz3-Sep-12 9:48 
GeneralMy vote of 5 PinmvpOriginalGriff3-Sep-12 9:35 
GeneralMy vote of 5 PinmvpMika Wendelius3-Sep-12 8:41 
GeneralMy vote of 3 PinmemberEd Nutting3-Sep-12 8:14 
GeneralRe: My vote of 3 PinmemberJeffrey T. Fritz3-Sep-12 8:21 
GeneralRe: My vote of 3 PinmemberEd Nutting3-Sep-12 8:39 
GeneralRe: My vote of 3 [modified] PinmemberAndreas Gieriet4-Sep-12 1:03 
I didn't see the original article, but I have a more relaxed view on using var, especially in connection with lengthly type names (and/or) where it is obvious or irrelevant what the type name is. I see it as a means of abstraction in such cases.
 
I've also experienced some places where var safes you trouble: some foreach constructs (e.g. with enums) were hard to debug until finally the light turned on that the enum type was the wrong one - with var that would have been caught by the compiler.
 
The reason for that is, that an explicit type in the foreach loop does an implicit cast - if that is possible, the cast is done - no matter if it is the "right" one or not. If you leave that to the compiler (i.e. write var), it would take what you get from the iterator and complain in the body if used differently.
 
Maybe we should have a tip/trick about discussing the pros and cons of var. And please, not a flame war Wink | ;-) There are reasons for and against. Use it wisely (others would say: "use your brain") - as holds for many features in any language.
 
[EDIT]
Just saw that one: Can the C# ‘var’ keyword be misused?[^]. It's short but covers mainly what I mean by abstraction above.
[/EDIT]
 
Cheers
Andi

modified 10-Sep-12 7:25am.

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

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

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