Skip navigation
top menu

Implicit conversions in C#

Yesterday I came across an interesting article: What's the opposite of Nullable. While the solution for Non-Nullability is interesting, the reason i'm blogging this is because the article also used a C# feature which i didn't know of: implicit conversions.

And guess what? Today I had a situation where I could use these implicit conversions. My app reads data from a CSV-file, so all the input are just strings. Until now that was just fine. However, at one part of my code I had to process one of the fields which has a fixed format. Say a field is a phonenumber and i need the country-prefix. So I created a PhoneNumber-class like this:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
public class PhoneNumber
{
  private readonly string _number;
 
  public PhoneNumber(string number)  {
      if (!new Regex(PHONE_NUMBER_REGEX).IsMatch(number))
      {
          throw new ArgumentException("Invalid phone number", "number");
      }      _number = number;
  }
  
  public string Prefix
  {    get { return GetPrefixFromNumber(...); }
  }
}

Now it is possible to create a (helper-)method in another class to get the prefix like this (this is just a simple example):

1
2
3
4
public string GetPrefix(PhoneNumber phoneNumber)
{
  return phoneNumber.Prefix;
}

But when you only have the phonenumber as a string, you'll still have to create an instance of PhoneNumber to be able to call the GetPrefix method:

1
var prefix = GetPrefix(new PhoneNumber("+32485123456"));

That is, until we add a method for implicit conversion to the PhoneNumber-class:

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
public class PhoneNumber
{
  private string _number;
 
  public PhoneNumber(string number)  {
      if (!new Regex(PHONE_NUMBER_REGEX).IsMatch(number)
      {
          throw new ArgumentException("Invalid phone number", "number");
      }      _number = number;
  }
  
  public string Prefix
  {    get { return GetPrefixFromNumber(...); }
  }
  
  public static implicit operator PhoneNumber(string number)
  {    return new PhoneNumber(number);
  }
}

Now it is possible to call the GetPrefix method with just a string. The string will be automagically converted to a PhoneNumber, unless it is invalid, in which case the ArgumentException will be thrown:

1
var prefix = GetPrefix("+32485123456");

Comments

No comments
Post new comment
The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options