Using C# Implicit Type Conversion

Categories: C#

I was recently required to connect to a SOAP-based web service that had a very nasty WSDL.  It contained tons of complex type definitions for objects that really didn’t need to exist (strings and decimals and integers would have been sufficient).  For example, here’s a snippet of a complex type defined in the WSDL that I needed to consume:

public partial class TOTAL_AMT_TypeShape : object, INotifyPropertyChanged 
    private decimal valueField;

    public decimal Value
        get { return this.valueField; }
            this.valueField = value;

    // snip...

This class is created by Visual Studio and is the proxy for the TOTAL_AMT_TypeShape object.  As you can probably surmise, this is simply a complex type wrapping a number (a C# decimal to be exact).  The name is awful, and the whole premise of requiring a complex type for a simple number amount (a dollar amount in this case) makes the use of this type really awkward:

decimal amount = 100000.0m;
TOTAL_AMT_TypeShape totalAmt = new TOTAL_AMT_TypeShape() { Value = amount };


Now imagine this like times 100.  It can get really ugly, really fast.

My solution was to rely on partial classes and implicit type conversion.  Implicit type conversion is a C# feature that allows you to convert between data types automatically by informing the compiler how to perform the conversion.  The conversion happens automatically and should only be used where the conversion will not result in any data loss or possibly throw an exception (if either of those scenarios exists, you should use an explicit cast conversion instead).  An example of an implicit conversion built into C# would be int to long conversion.  Since an int always fits inside a long, we can assign a long variable to an int without any special effort.  The opposite is not true, however, and we’d need to explicitly cast.

Here’s my partial class with the implicit conversion operator added:

public partial class TOTAL_AMT_TypeShape
    public static implicit operator TOTAL_AMT_TypeShape(decimal value) 
        return new TOTAL_AMT_TypeShape() { Value = value };


The implicit conversion operator overload is defined for converting a decimal to a TOTAL_AMT_TypeShape (the output type is always the name of overload method).  We could also go the other way (convert a TOTAL_AMT_TypeShape into a decimal, but I didn’t need to in my case).  And because C# allows partial class definitions, if our proxy object definition changes because of a WSDL refresh, we keep our partial intact and the code for the implicit conversion won’t be overwritten.

Here’s how we’d use it now:

TOTAL_AMT_TypeShape totalAmt = 100000.0m;


Nice and neat.

No Comments