Conversion operators in C#

This is a short post about the not so well known implicit and explict operators in C#. These operators are used for user-defined conversions of custom types, and their existence is an often overlooked feature of C# (at least overlooked by me, until recently).

An implicit cast occurs automatically when an implicit conversion operator has been defined and the two data types are compatible. An explicit cast is used when the two data types are not entirely compatible and requires a cast.

For example, after we defined an implict cast from List to DmCollection like this:

 public static implicit operator DmCollection<T>(List<T> list)
 {
      return new DmCollection<T>(list);
}

we can now cast a List to a DmCollection:

List<T> list = new List<T>();
DmCollection<T> col = (DmCollection<T>) list;

An example of an implicit operator for the conversion of a double to a Vector class:

public static implicit operator double(Vector v)
{
    return v.Length;
}

we can now assign a Vector to a variable of type double without the need for an explicit cast:

Vector v = new Vector(5, 5);
double d = v;

Read more:

Leave a Reply





Human Verification