.NET Tips and Tricks

Blog archive

Adding Your Own Explicit Type Conversions in C#

In my previous tip, I showed how to add an implicit conversion to C#. But there are two rules you should follow when defining an implicit conversion: 1) An implicit conversion should never throw an error, and 2) It should never lose information. If neither of those conditions is true, you should declare the conversion as explicit, as this code does:

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

  public static explicit operator PremiumCustomer(DeadbeatCustomer dbc)
  {
    PremiumCustomer pc = new PremiumCustomer();
    pc.CustomerId = dbc.CustomerId;
    pc.Name = dbc.Name;
    if (pc.CanUseCredit != true)
    {
      pc.CanUseCredit = dbc.CanUseCredit;
    }
    else
    {
      throw new Exception("Can't convert DeadbeatCustomers with bad credit");
    }
    return pc;
  }
}

The code to convert a DeadbeatCustomer to a PremiumCustomer would need an explicit cast and look, like this:

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

Posted by Peter Vogel on 02/28/2014


comments powered by Disqus

Featured

Subscribe on YouTube