#1,058 – Custom Implicit Conversions in Both Directions

When you define a custom implicit (or explicit) conversion, you can define a conversion both to and from a particular type.

In the example below, we define custom implicit conversions that allow implicitly converting from an int to a Dog, as well as converting from a Dog to an int.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        // Implicitly convert from int to Dog
        public static implicit operator Dog(int value)
        {
            return new Dog(string.Format("Dog-" + value.ToString()), value);
        }

        // And implicitly convert from Dog to int
        public static implicit operator int(Dog d)
        {
            return d.Age;
        }
    }

With these conversions, we can now do the following:

            // int to Dog
            int i1 = 12;
            Dog dog1 = i1;

            // Dog to int
            Dog dog2 = new Dog("Bowser", 5);
            int i2 = dog2;

1058-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,058 – Custom Implicit Conversions in Both Directions

  1. Pingback: Dew Drop – March 21, 2014 (#1748) | Morning Dew

Leave a comment