#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

Advertisements

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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: