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

Can struct have constructor c#?

0 Answers  


What is the difference between virtual method and abstract method?

0 Answers  


What is serialization in unity?

0 Answers  


Hoe can i connect the table into the c# application?

2 Answers  


How many types of polymorphism are there?

0 Answers  


Explane each and every methods of nterface Queue? Explain About performance issues on retrieving records

0 Answers   DELL,


What are the steps to make an assembly to public?

0 Answers  


What's different between c# and c/c++?

0 Answers  


What is double c#?

0 Answers  


how can i display crystalreport in button click? am working with VS2005

1 Answers  


What is the different types of private assembly and shared assembly?

0 Answers  


How do you declare a method in c#?

0 Answers  


Categories