This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing

This post has been migrated, original date 20 Jul 2009 Using implicits can improve the quality of your code and how easy it is to read the code. Lets take for example a simple address, this class is going to have street, town and postcode properties. I want to ensure that only valid postcodes are passed to the class but I still want to be able to assign the postcodes easily. This is where implicits come in. Below is the Postcode class, you can see it has two implicit methods, one to convert a string to the postcode class and one to convert the postcode class to a string.
    public class Postcode
    {
        string _postcode;
        public Postcode(string postcode)
        {
            if (!Regex.IsMatch(postcode, @"^[\w\s\d]*$"))
                throw new ApplicationException("Not a valid postcode");

            _postcode = postcode;
        }
        public override string ToString()
        {
            return _postcode;
        }
        public static implicit operator Postcode(string postcode)
        {
            return new Postcode(postcode);
        }
        public static implicit operator string(Postcode postcode)
        {
            return postcode.ToString();
        }
    }
An here is my address class:
    public class Address
    {
        public string Street { get; set; }
        public string Town { get; set; }
        public Postcode Postcode {get;set;}
    }
I can then assign and read the postcode as shown below. I know that only a valid postcode can be assigned to the class because of the regular expression. Using this method there is no way an invalid postcode could be passed to the property.
            Address newAddress = new Address();
            newAddress.Street = "3 Nice Road";
            newAddress.Town = "Smallville";
            newAddress.Postcode = "BAZ ER1";

            Console.WriteLine(newAddress.Postcode);