use of operator overloading of implicit & explicit operators?

Answer Posted / karthikeyant

Implicit:

By eliminating unnecessary casts, implicit conversions can
improve source code readability. However, because implicit
conversions can occur without the programmer's specifying
them, care must be taken to prevent unpleasant surprises.
In general, implicit conversion operators should never
throw exceptions and never lose information so that they
can be used safely without the programmer's awareness. If a
conversion operator cannot meet those criteria, it should
be marked explicit.

class MyType
{
public static implicit operator int(MyType m)
{
// code to convert from MyType to int
}
}

MyType x;
// implicitly call MyType's MyType-to-int conversion
operator
int i = x;

Explicit:
declares a user-defined type conversion operator that must
be invoked with a cast. For example, this operator converts
from a class called Fahrenheit to a class called Celsius:

// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Farenheit f)
{
return new Celsius((5.0f/9.0f)*(f.degrees-32));
}

Farenheit f = new Farenheit(100.0f);
Celsius c = (Celsius)f;

Is This Answer Correct ?    3 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is difference between asp net and c# net?

688


What is readline library?

719


What is difference between value and reference types in C#.NET

758


Is null == null c#?

651


What is a static property. Give an example?

716


How do you clear a list in c#?

686


What kind of the information stored inside the assembly?

768


What is the main purpose of delegates in c#?

739


can you allow a class to be inherited, but prevent the method from being over-ridden?

742


How we convert private assembly into public assembly?

722


What is the difference between overriding and overloading in systemverilog?

697


How long does it take to get a loop recorder put in?

659


How is lazy loading achieved?

694


Is it possible to have a static indexer in c#?

726


Why are strings in c# immutable?

713