#1,057 – Custom Explicit Conversions

You can define both implicit and explicit custom conversions for a type that you author.

In the code fragment below, we’ve defined an implicit conversion from int to Dog and an explicit conversion from Cow to Dog.

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

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

We can now do the following:

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

            // Implicit conversion from int to Dog
            Dog anotherDog = 42;

            // Explicit conversion from Cow to Dog
            Dog nowADog = (Dog)someCow;

If we try assigning a Cow instance to a variable of type Dog without the cast operator, we’ll get a compile-time error indicating that there is no implicit conversion between Cow and Dog.

1057-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #1,057 – Custom Explicit Conversions

  1. Pingback: Dew Drop – March 20, 2014 (#1747) | Morning Dew

  2. James Curran says:

    You’re using String.Format in a rather questionable way:
    string.Format(“Dog-” + value.ToString())

    could be better written as:

    string.Format(“Dog-{0}”, value)

    or

    “Dog-” + value.ToString()

    or even just:

    “Dog-” + value

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: