.NET Tips and Tricks

Blog archive

Adding Your Own Implicit Type Conversions in C#

You may find that you have two classes that you frequently need to convert between. You could repeat the conversion code wherever you need it, or put it in some random class. Or you could add a new implicit conversion to one of the classes.

For instance, if you need to frequently convert a DeadbeatCustomer into a PremiumCustomer, just put the code inside a conversion method in the PremiumCustomer class that accepts a DeadbeatCustomer. To add a conversion method to a class, first define a public static method, followed by the implicit keyword, the operator keyword, and the method's return type. The method must accept a parameter of the type you want to convert. Here's the code for the DeadbeatCustomer to PremiumCustomer conversion:

public class PremiumCustomer
{
  public string CustomerId {get; set;}
  public string Name {get; set;}
  public bool CanUseCredit {get; set;}

  public static implicit operator PremiumCustomer(DeadbeatCustomer dbc)
  {
    PremiumCustomer pc = new PremiumCustomer();
    pc.CustomerId = dbc.CustomerId;
    pc.Name = dbc.Name;
    pc.CanUseCredit = true;
    return pc;
  }
}

This code will automatically invoke your conversion method and handle the conversion:

DeadbeatCustomer db = new DeadbeatCustomer();
PremiumCustomer pc = db;

Be warned, though: I've made some assumptions here that I'll return to in my next tip.

Posted by Peter Vogel on 02/25/2014


comments powered by Disqus

Featured

Subscribe on YouTube