use of operator overloading of implicit & explicit operators?



use of operator overloading of implicit & explicit operators?..

Answer / 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

More C Sharp Interview Questions

Who is a accessibility modifier “protected internal” available to ?

0 Answers   Siebel,


Which .gang of four. Design pattern is shown below?

0 Answers  


List the 5 different access modifiers in c#?

0 Answers  


Does c# have its own class library?

0 Answers  


How does insertion sort work?

0 Answers  






How do you determine whether a string represents a numeric value?

0 Answers  


Why is static constructor called first?

0 Answers  


1)what is difference between char and varchar in sql server 2005 2) what is composite key and candidate key 3) what is temporary table and derived table 4) how to calculate difference between two dates

1 Answers   Wipro,


What is method overriding in c#

0 Answers  


What is InterFace???

12 Answers  


What is difference between value and reference types?

5 Answers   Accenture,


What is the default scope of a class in c#?

0 Answers  


Categories