#1,055 – Defining Your Own Implicit Conversions
March 18, 2014 1 Comment
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).
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;