In my last article about type casting, I explained narrow and widening conversions along with as and is operators. In this article, we shall take casting to a whole new level. At the end, you will learn how readability of code can be improved with implicit and explicit operators.
Implicit conversions
Implicit conversions are easier to use and understand. For example, assigning an integer to a double is implicit conversion and of course there is no data loss.
- int val1 = 10;
- double val2 =val1;
- int val1 = 10;
- double val2 =val1;
- int val3 = (int) val2;
Consider the code below and casting done
- double amount=10;
- Money money= new Money(amount);
- Int convertedAmount=Convert.ToInt16(money.Amount);
- //Money class
- class Money
- {
- public double Amount {get;set;}
- public Money(double amount)
- {
- Amount=amount;
- }
- }
By eliminating unnecessary casts, implicit conversions can improve source code readability. Nevertheless; we can use implicit and explicit operators at the class side to convert a value from one type to another. Let’s see a few examples to understand the concept better.
Implicit
Amount is a property of type double and we create a new object of class Money, we pass in to constructor the amount. When we want to use the value of the amount, we access it over the money object created (money.Amount). C# provides implicit operator which facilitates this conversion at the class end.
- public static implicit operator double(Money m)
- {
- return m.Amount;
- }
- Usage:
- Money m = new Money(12.3);
- double amount = m;
With the help of implicit operator, readability of code is improved and now class Money is responsible for all the conversion needed.
Explicit
Let’s understand it the other way round. Amount cannot be converted in to Money; therefore, we need explicit casting.
- public static explicit operator Money(double m)
- {
- Money money = new Money(m);
- return money;
- }
- double amt = 16.5;
- //Explicit Conversion
- Money money = (Money) amt;
- Console.WriteLine(money.Amount);
However, to prevent unexpected results, care must be taken care dealing with implicit conversions because it does not require programmers to explicitly cast from one type to the other. However, explicit conversion is quite obvious with casting.

Pramod GuptaPosted Oct 1, 2015, 1:51 AM
Gud one
Ankit BansalPosted Oct 1, 2015, 12:39 AM
Nice .. thanks for sharing..
Santhakumar MunuswamyPosted Sep 30, 2015, 3:34 PM
Good one
Shridhar SharmaPosted Sep 30, 2015, 12:32 PM
good one
Raja TPosted Sep 30, 2015, 9:36 AM
Nice.. Thanks for sharing
Pankaj Kumar ChoudharyPosted Sep 30, 2015, 9:21 AM
Nice Explanation Sir...........
Nilesh JadavPosted Sep 30, 2015, 9:16 AM
Nice post
Sujeet SumanPosted Sep 30, 2015, 8:32 AM
Nice Article................
Karthikeyan KPosted Sep 30, 2015, 4:08 AM
Good one...Thanks for sharing
RakeshPosted Sep 30, 2015, 3:23 AM
Good Share
Harshad PansuriyaPosted Sep 30, 2015, 3:19 AM
Nice One