#1,056 – Custom Implicit Conversions between Reference Types

You can define your own implicit conversions between value types.  You can also define a custom implicit conversion to allow implicitly converting from any type to a given reference type.

In the example below, we add methods to a Dog type to allow implicit conversions from both Cow and int types to the Dog type.

        // Implicitly convert from Cow to Dog
        public static implicit operator Dog(Cow cow)
        {
            return new Dog(string.Format(cow.Name + " IWasACow"), cow.Age);
        }

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

We can now do the following implicit conversions:

            Cow someCow = new Cow("Bessie", 3);

            // Cow becomes Dog
            Dog nowADog = someCow;

            // Number 42 becomes Dog
            Dog anotherDog = 42;

1056-001

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

One Response to #1,056 – Custom Implicit Conversions between Reference Types

  1. Pingback: Dew Drop – March 19, 2014 (#1746) | Morning Dew

Leave a comment