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 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:
var prefix = GetPrefix(new PhoneNumber("+32485123456"));
That is, until we add a method for implicit conversion to the PhoneNumber-class:
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:
var prefix = GetPrefix("+32485123456");
Comments
There are no comments.