Introduction 

In this article I'm going to describe about how to use type conversion operators (implicit & explicit) in user-defined classes. We commonly come across situations in which a same real-world entity is represented in two different classes. For ex. when integrating two sub-systems into one, we see an entity is represented as Author in one sub-system and as Writer in other.  Although, in the combined system both represents the same real-world object, it is difficult to represent them as one throughout because of the extensive code change and dependencies. 

In these situations normally when the objects move between systems at one point we have to convert the Author to Writer and vice-versa. Usually we go ahead creating helper classes or extension methods to convert one into other. But, in this article I'm going to show you how we can use the implicit/explicit operators to make the conversions(Author to Writer or Writer to Author) more easy! 

Background  

Casting  

Conversion between data types can be done in two ways by casting,

  • Implicit casting 
  • Explicit casting  

Implicit Casting 

Implicit Casting doesn't require a casting operator. This casting is normally used when converting data from smaller integral types to larger or derived type to base type. 

int x = 123;
double y = x;

In the above statement, the conversion of data from int to double is done implicitly, in other words programmer don't need to specify any type operators. 

Explicit Casting 

Explicit Casting requires a casting operator. This casting normally used when converting a double to int or base type to derived type. 

double y = 123;
int x = (int)y; 

In the above statement we have to specify the type operator (int) when converting from double to int else compiler will throw error. You can learn more about casting here.  

Conversion Operators  

Conversion operators helps to cast user-defined types from one to other much like the basic types. For implicit or explicit conversion we have to create a static method in the corresponding class having method name as the type it returns including the keyword that says implicit or explicit. To know more follow this link.   

Let's see an example!  

Let's see an example of how we can implement the casting mechanism in our user-defined classes using Conversion Operators

public class Author
{
    public string First;
    public string Last;
    public string[] BooksArray;
}

public class Writer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public IList Books { get; set; }
} 

      We have two classes Author & Writer used in different sub-systems that represents the same real-world entity. Let's see how we can implement the implicit or explicit casting in the classes. [Note: It's not allowed to implement both the casting in a same class. We can implement either implicit or explicit]  

Author author2 = (Author)writer; //explicit casting 
Author author1 = writer; //implicit casting 

First let's try the explicit casting,  

  •  Create a static method in the Author class. The name of the method should be same as the type it's going to be casted in our case it is Writer. For explicit casting we need explicit keyword should be included in the method definition.  
public static explicit operator Writer(Author a)
{
    //implementation goes here..
}   

  • Create an instance of Writer class and populate it's fields from the passed Author instance. 

public static explicit operator Writer(Author a)
{
    return new Writer
    {
        FirstName = a.First,
        LastName = a.Last,
        Books = a.BooksArray != null ? a.BooksArray.ToList() : null
    };
}  

That's it! Now wherever we need to cast Author to Writer explicitly it's as simple as below,  

Author a = new Author
{
    First = "Vijaya",
    Last = "Anand",
    BooksArray = new string[] { "book1" }
};
Writer w = (Writer)a; //explicitly casting from Author to Writer. 

We can do the same thing in the Writer class to cast it to Author.  

For implicit casting we have to follow the same steps as above except we have to use the implicit keyword instead of explicit, 

public class Author
{
    public string First;
    public string Last;
    public string[] BooksArray;

    public static implicit operator Writer(Author a)
    {
        return new Writer
        {
            FirstName = a.First,
            LastName = a.Last,
            Books = a.BooksArray != null ? a.BooksArray.ToList() : null
        };
    }
} 

Now implicit casting is as simple as, 

Author a = new Author
{
    First = "Vijaya",
    Last = "Anand",
    BooksArray = new string[] { "book1" }
};
Writer w = a; //implicitly casting from Author to Writer. 

Whenever we do the implicit or explicit casting the corresponding static method will be called. That's all! Hope you enjoyed. Please drop your comments and votes.   

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架