Click here to Skip to main content
Click here to Skip to main content

Coversion operators

, 25 May 2007
Rate this:
Please Sign up or sign in to vote.
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:

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:

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

Here is a program that illustrates this conversion operator:

// 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:

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:

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:

// 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)

About the Author

ali_reza_zareian
Software Developer
Iran (Islamic Republic Of) Iran (Islamic Republic Of)
Where is the truth?

Comments and Discussions

 
GeneralSpelling of title is incorrect PinmemberMichael Freidgeim16-Oct-07 19:37 
GeneralNice Pinmemberkordy1110-Sep-07 9:24 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 25 May 2007
Article Copyright 2007 by ali_reza_zareian
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid