Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Conversion Operator Overloading in C# (OOP’s) – Part 19

Posted by Ravi Varma Thumati on July 13, 2009

C# Conversion Operator Overloading

In the article, C# Numeric Type Conversion, Casting permits a value of one type to be converted to another data type so that it can be used in a calculation or method or in any other situation where the value’s current data type is unsuitable.

The conversion of data types provided by casting can be either implicit or explicit. 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 the source type to be prefixed with a cast operator. This operator is the desired data type enclosed in parentheses ().

The following code sample shows a comparison of conversion using implicit and explicit casts for basic numeric data types. Note the requirement for the cast operator for the second conversion.

uint integer = 100;

long longInteger;

// Implicit cast

longInteger = integer;

// Explicit cast

integer = (uint)longInteger;

When you create a new class, it does not possess the capabilities to be cast to other data types. Each possible cast must be defined within the class and declared as either implicit or explicit. As can be seen in the above example code, the implicit cast can be easier to read and can provide neater code. However, it is not immediately apparent to the reader that a conversion is occurring and so implicit casting can hide problems that would be more apparent if an explicit cast operator were used.

As a rule of thumb, implicit casting should only be used where there is no risk of data loss or an exception being thrown. Explicit casting should be used in all other situations. This is demonstrated in the above code. Implicit casting from the smaller integer to the larger integer is risk-free as all possible values can be converted. For conversion from the large, signed integer to the smaller, unsigned integer there is a risk that the value will lose its sign or be too large to be converted so explicit casting is more appropriate.

There are some restrictions to overloading the conversion operators. The key restrictions are:

  • You may not create operators that convert a class to the object data type. Conversion to object is provided automatically to permit boxing and unboxing.
  • You may not create operators that convert a class to a defined interface. If conversion to an interface is required, the class must implement the interface. Interfaces will be described later in the C# Object-Oriented Programming tutorial.
  • You may not create operators that convert from a base class into a class derived from that base class. Class inheritance will be described later in this tutorial.

Creating an Implicit Conversion Operator

The implicit and explicit cast operators are unary operators and, as such, are overridden using a similar syntax as other basic unary operators. The following syntax is for the implicit conversion operator:

public static implicit operator result-type(op-type operand)

The result-type is the data type for the return value of the operation, ie. the target type for the cast. The op-type is the data type for the operand that is to be converted. One of the two data types must be the same as the class in which the declaration is made.

Adding Double Conversion to the Vector Class

Using the syntax described above, we will now add an implicit conversion operator to the Vector class. This operator will cast a Vector to a double-precision floating point number representing the length of the Vector. The length calculation is already present as a property of the class so we will reuse this functionality. To add the new conversion operator, add the following code to the Vector class:

public static implicit operator double(Vector v)

{

return v.Length;

}

You can test the new conversion operator by modifying the Main method of the program:

static void Main(string[] args)

{

Vector v = new Vector(5, 5);

double d = v;

Console.WriteLine(d);           // Outputs 7.07106781186548

}

Creating an Explicit Conversion Operator

The syntax for creating an explicit conversion operator is similar to that of the implicit version. Only the implicit keyword is changed. The syntax is therefore:

Public static explicit operator result-type(op-type operand)

Adding Single Conversion to the Vector Class

We will use the explicit version of the conversion operator syntax to allow the Vector to be cast as a single-precision floating point value representing the vector’s length. The choice of explicit operator is due to the loss of accuracy of the number when the length is converted from a double to a float.

To add the new conversion operator, add the following code to the Vector class:

public static explicit operator float(Vector v)

{

return (float)v.Length;

}

The new conversion can be tested using the updated Main method below. Note the loss of accuracy that occurs when the vector’s length is cast.

static void Main(string[] args)

{

Vector v = new Vector(5, 5);

float f = (float)v;

Console.WriteLine(f);           // Outputs 7.071068

}

NB: The use of the (float) operator is required in this example as the conversion has been defined as explicit. Removing this cast operator causes a compiler error.

Advertisements

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: