Click here to Skip to main content
11,438,226 members (78,572 online)
Click here to Skip to main content

Understanding Implicit Operator Overloading in C#

, 15 Aug 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
Explains the implicit operator overloading in C#

Introduction

Everyone knows that in .NET, byte, char, int, long, etc. are value data types and string is a reference data type. Even though it is a reference type, string behaves much like a value type. In other words, it can directly accept values and doesn't require new to create an instance. For example:

string name = "M. Aamir Maniar"; //Directly accepts the value.

So far so good. Everyone is well acquainted with this basic demeanor of the string class. But the fact is that, most of them don't know how to incorporate such things into their own classes. To explain this concept, let's think about the Currency class. Currency class fundamentally has two properties:

  • Sign //String: Holds the currency sign like $,£,¥,€,Rs., etc.
  • Value //Decimal: Holds the currency value

The class has one constructor which accepts two parameters, i.e. value and sign which set the respective properties of the class. So if you are creating an instance of the class, you will do that in the following manner:

Currency cur = new Currency(100.50, "$");
Right? Assuming $ is a default currency sign, don't you think this is a bit tedious way to instantiate such kind of data type. What about the following approach:

Currency cur = 100; //Currency directly accepts value
//Instantiating currency using currency sign.
Currency cur = "€"; 
cur.Value = 100;    //Implicit typecasting from number to Currency

//What about this
long lCur = cur;    //Implicit typecasting from Currency to long 
decimal dCur = cur; //Implicit type casting from Currency to decimal 

The Implicit Operator

If you want to incorporate such a feature, an implicit operator overloading comes into the picture. Yes, there is something called implicit operator overloading. According to MSDN, an implicit keyword is used to declare an implicit user-defined type conversion operator. In other words, this gives the power to your C# class, which can accepts any reasonably convertible data type without type casting. And such a kind of class can also be assigned to any convertible object or variable. If you want to create an implicit operator function, here is a signature of creating them in C#.

«access specifier» static implicit operator «converting type» («convertible type» rhs)

The above signature states that the operator accepts «convertible type» and converts into «converting type».

The following code shows you how to create them:

/// <span class="code-SummaryComment"><summary></span>
/// Creates Currency object from string supplied as currency sign.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The currency sign like $,£,¥,€,Rs etc. </param></span>
/// <span class="code-SummaryComment"><returns>Returns new Currency object.</returns></span>
public static implicit operator Currency(string rhs)
{ 
    Currency c = new Currency(0, rhs); //Internally call Currency constructor
    return c;

}

/// <span class="code-SummaryComment"><summary></span>
/// Creates a currency object from decimal value. 
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The currency value in decimal.</param></span>
/// <span class="code-SummaryComment"><returns>Returns new Currency object.</returns></span>
public static implicit operator Currency(decimal rhs)
{
    Currency c = new Currency(rhs, NumberFormatInfo.CurrentInfo.CurrencySymbol);
    return c;

/// <span class="code-SummaryComment"><summary></span>
/// Creates a decimal value from Currency object,
/// used to assign currency to decimal.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The Currency object.</param></span>
/// <span class="code-SummaryComment"><returns>Returns decimal value of the currency</returns></span>
public static implicit operator decimal(Currency rhs)
{
    return rhs.Value;
}

/// <span class="code-SummaryComment"><summary></span>
/// Creates a long value from Currency object, used to assign currency to long.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="rhs">The Currency object.</param></span>
/// <span class="code-SummaryComment"><returns>Returns long value of the currency</returns></span>
public static implicit operator long(Currency rhs)
{
    return (long)rhs.Value;
}

Behind the Scene

Such kind of implicit operator overloading is not supported by all languages, then how does C# incorporate such a nice feature. The answer lies in an assembly code generated by the C# compiler. The following table shows the C# syntax with the corresponding IL syntax.

C# declaration IL Declaration
public static implicit operator 
	Currency(decimal rhs) 
.method public hidebysig specialname static 
class Currency op_Implicit(valuetype [mscorlib]
System.Decimal rhs) cil managed
public static implicit operator 
	decimal(Currency rhs)
.method public hidebysig specialname static 
valuetype [mscorlib]System.Decimal op_Implicit
(class Currency rhs) cil managed

The IL syntax in the above table makes it clear that the C# compiler generates op_Implicit function which returns «converting type» and accepts «converting type».

Hope this article is useful to you.

Visit my blog here.

History

  • 15th August, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

aamironline
Chief Technology Officer Maniar Technologies Pvt Ltd
India India
No Biography provided
Follow on   Twitter

Comments and Discussions

 
NewsThanks Pin
mishenkovks11-Dec-07 2:39
membermishenkovks11-Dec-07 2:39 
GeneralThanks Pin
mishenkovks11-Dec-07 2:38
membermishenkovks11-Dec-07 2:38 
GeneralLosing information Pin
Jeffrey Sax20-Aug-06 9:03
memberJeffrey Sax20-Aug-06 9:03 
Even though your article has noble intentions, it falls short on one key issue: it breaks the #1 rule of conversion operators:
If the conversion from type A to type B causes some information to be lost, always use an explicit conversion. If the conversion from type A to type B is guaranteed to preserve all information, you may use an implicit conversion.
In this case, the only conversions that can be implicit are from long and from decimal to Currency. All other conversions lose the currency symbol (the 'unit') and may lose data (decimal to long).

Then there is the #1 rule of using "syntactic sugar":
Only use syntactic sugar if it does not make the code more difficult to read.
In this case, currency is thought of as a value more than something that has a unit. It is therefore acceptable to assign a value to a Currency object. On the other hand, it is not immediately obvious what assigning a string to a currency object means. You should not allow the conversion from string to currency.

Finally, you should be aware that defining implicit conversions can have unintented consequences[^]. Adding an implicit conversion operator may break existing code.

Jeffrey

Everything should be as simple as possible, but not simpler.
    -- Albert Einstein

Numerical components for C# and VB.NET Numerical .NET Blog

GeneralRe: Losing information Pin
M Aamir Maniar20-Aug-06 17:20
memberM Aamir Maniar20-Aug-06 17:20 
GeneralRe: Losing information Pin
stano11-Feb-07 5:43
memberstano11-Feb-07 5:43 
GeneralRe: Losing information Pin
MartinFister18-Apr-10 6:15
memberMartinFister18-Apr-10 6:15 
QuestionHow to: Define a Conversion Operator in VB Pin
red baron16-Aug-06 11:09
memberred baron16-Aug-06 11:09 
AnswerRe: How to: Define a Conversion Operator in VB Pin
M Aamir Maniar16-Aug-06 16:49
memberM Aamir Maniar16-Aug-06 16:49 
GeneralNice article and a suggestion Pin
Dustin Metzgar16-Aug-06 3:54
memberDustin Metzgar16-Aug-06 3:54 
GeneralRe: Nice article and a suggestion Pin
M Aamir Maniar16-Aug-06 6:23
memberM Aamir Maniar16-Aug-06 6:23 

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 | Terms of Use | Mobile
Web01 | 2.8.150506.1 | Last Updated 15 Aug 2006
Article Copyright 2006 by aamironline
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid