Click here to Skip to main content
15,888,218 members
Articles / Programming Languages / C#

Conversion operators

Rate me:
Please Sign up or sign in to vote.
3.43/5 (11 votes)
23 Jan 2015CPOL2 min read 41.1K   23   5
A conversion operator converts an object of your class into another type

Introduction

In some situations, you will want to use an object of a class in an expression involving other types of data. Sometimes, overloading one or more operators can provide the means of doing this. However, in other cases, what you want is a simple type conversion from the class type to the target type. To handle these cases, C# allows you to create a special type of operator method called a conversion operator. A conversion operator converts an object of your class into another type. In essence, a conversion operator overloads the cast operator. Conversion operators help to fully integrate class types into the C# programming environment by allowing objects of a class to be freely mixed with other data types, as long as a conversion to those other types is defined. There are two forms of conversion operators, implicit and explicit. The general form for each is shown here:

C#
public static operator implicit target-type(source-type v) 
{ 
    return value; 
}

public static operator explicit target-type(source-type v) 
{ 
    return value; 
}

Here, target-type is the target type that you are converting to, source-type is the type that you are converting from and value is the value of the class after conversion. The conversion operators return data of type target-type and no other return type specifier is allowed. If the conversion operator specifies implicit then the conversion is invoked automatically, such as when an object is used in an expression with the target type. When the conversion operator specifies explicit, the conversion is invoked when a cast is used. You cannot define both an implicit and an explicit conversion operator for the same target and source types.

Using the code

To illustrate a conversion operator, we will create one for the Student class. Suppose you want to convert a string to the object type. To accomplish this, you will use an implicit conversion operator that looks like this:

C#
public static implicit  operator Student(string str)
{
    return new Student(str);
}

Here is a program that illustrates this conversion operator:

C#
// An example that uses an implicit conversion operator.

   using System; 
   using System.Collections.Generic; 
   using System.Text; 

   namespace operatoreOverload 
   {   
       class Student 
       { 
           private string FullName = ""; 
           public Student(string str) 
           { 
              FullName = str; 
           } 
           public static implicit operator Student(string str) 
           { 
              return new Student(str); 
           } 
           public static implicit operator string(Student stu) 
           {
              return stu.FullName; 
           } 
       } 
       class Program 
       { 
           static void Main(string[] args) 
           { 
               Student stud="Implicit define"; 
               string str = stud; 
              Console.WriteLine(str); 
              Console.ReadKey(); 
            } 
        } 
    }     

This program displays the output:

C#
Implicit define

As the program illustrates, when we use a string in an object experssion such as Student stud="Implict define", the conversion is applied to the string. In this specific case, the conversion returns an object that sets the Fullname field. However, when an expression does not require a conversion to the Student object, the conversion operator is not called. Remember that in the previous example we converted the Student object to the string by this code:

C#
public static implicit operator string(Student stu) 
{
    return stu.FullName; 
} 

Alternatively, you can create an explicit conversion operator that is invoked only when an explicit cast is used. An explicit conversion operator is not invoked automatically. For example, here is the previous program reworked to use an explicit conversion to the Student object and string:

C#
// An example that uses an implicit conversion operator.

   using System; 
   using System.Collections.Generic; 
   using System.Text; 

   namespace operatoreOverload 
   {   
       class Student 
       { 
           private string FullName = ""; 
           public Student(string str) 
           { 
              FullName = str; 
           } 
           public static explicit operator Student(string str) 
           { 
              return new Student(str); 
           } 
           public static explicit operator string(Student stu) 
           {
              return stu.FullName; 
           } 
       } 
       class Program 
       { 
           static void Main(string[] args) 
           { 
               Student stud=(Student)"Implicit define"; 
               string str = (string)stud; 
              Console.WriteLine(str); 
              Console.ReadKey(); 
            } 
        } 
    }

History

  • 25 May, 2007 - Original version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
Where is the truth?

Comments and Discussions

 
GeneralMy vote of 2 Pin
Youzelin26-Jan-15 21:32
Youzelin26-Jan-15 21:32 
Question...and misleading Pin
phil.o23-Jan-15 2:33
professionalphil.o23-Jan-15 2:33 
One cannot recommend to mess with implicit operators when there already is an existing and approved solution. In this case, it's sufficient for the Student class to override the ToString() method. This will be effective in the debugger, and in methods which use format-strings whith placeholders.

IMHO, implementing implicit operators should be reserved to value types conversions which cannot be ambiguous (like, for example, a complex number from a single real value: we can assume the value is the real part of the complex, and that its imaginary part is zero).
For classes, it is not suitable to have implicit conversions lying around everywhere; it defeats the strongly-typed orientation of the language, and can introduce some confusions and errors if you do not take care of how you implement them. For example, in your submission, a new student is created each time the implicit operator is called. But what if there is already a Student with this name? You will end up with two instances of Student with the same name, of which you may think they are one and only one entity.
GeneralSpelling of title is incorrect Pin
Michael Freidgeim16-Oct-07 19:37
Michael Freidgeim16-Oct-07 19:37 
GeneralNice Pin
kordy1110-Sep-07 9:24
kordy1110-Sep-07 9:24 
GeneralRe: Nice Pin
Youzelin26-Jan-15 21:32
Youzelin26-Jan-15 21:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.