Implicit and explicit conversion in c#

When converting from one type, obviously, there can be size difference between the source and destination.

If the destination is larger than the source then there may not be dataloss because of the conversion, if the other case if the source type is larger than the destination then part of the data may be lost during the conversion. Such conversions should not occure without being noticed by the programmer. So implicit and explicit keywords are used in C# to determine whether it is mandatory to specify the 'cast' during a conversion.
If the conversion is implicit, then you dont have to specify the cast; otherwise you should.

Eg:


class Alpha
{
int data1;
int data2;

public static implicit Alpha(int n)
{
Alpha a=new Alpha();
a.data1=n;
return a; //here the value of n fully becomes part of the destination. ie. no data loss.
}


public static explicit int(Alpha a)
{
return a.data1; // here only data1 is returned. and data2 is lost because of the conversion

}

}


You can access the data as follows.


Alpha a = 25; //implicit conversion - no casting

//int n = a; // ERROR - without casting

int n = (int) a; //explicit conversion - with casting


Comments

Guest Author: sharath25 Feb 2013

Is it that we need to have the "operator" keyword?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: