This is a mirror of official site: http://jasper-net.blogspot.com/

Type conversions with implicit and explicit operators

| Thursday, April 7, 2011
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; }

Read more: Codeproject

Posted via email from Jasper-net

0 comments: