Tag: c# ¦ Atom ¦ RSS

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:

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):

public …