#1,055 – Defining Your Own Implicit Conversions

Suppose that you define a new value type, for example the TimedInteger type shown below.

    public struct TimedInteger
    {
        private int theInt;
        private DateTime whenCreated;

        public TimedInteger(int value)
        {
            theInt = value;
            whenCreated = DateTime.Now;
        }
    }

You can now create instances of this type as follows:

            TimedInteger ti = new TimedInteger(5);

You can’t directly assign an integer to a variable of type TimedInteger because no implicit conversion exists between an integer literal and your type.  (Between an int and your type).
1055-001

To allow this assignment, you can define a custom implicit conversion for your type.  The code below allows an implicit conversion from an int to a TimedInteger.

        public static implicit operator TimedInteger(int value)
        {
            return new TimedInteger(value);
        }

You can now directly assign an integer literal, because there is an implicit conversion between int and TimedInteger.

            TimedInteger ti = 5;

1055-002

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.

One Response to #1,055 – Defining Your Own Implicit Conversions

  1. Pingback: Dew Drop – March 18, 2014 (#1745) | 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 )

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: