#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

Advertisements