Why can't coexist implicit and explicit operator of the same type in C#? -


this question has answer here:

why can not coexist in same class 2 operators (explicit , implicit) of same type? suppose have following:

public class fahrenheit {     public float degrees { get; set; }      public fahrenheit(float degrees)      {         degrees = degrees;     }      public static explicit operator celsius(fahrenheit f)     {         return new celsius(tocelsius(f.degrees));     }      public static implicit operator celsius(fahrenheit f)     {         return new celsius(tocelsius(f.degrees));     } }  public class celsius {     public float degrees { get; set; }     public celsius(float degrees)      {         degrees = degrees;     }  } 

so can give client possibility use of either of 2 ways, example:

fahrenheit f = new fahrenheit(20); celsius c1 = (celsius)f; celsius c2 = f; 

is there special reason why not allowed or convention avoid misuse of programmer?

according overloading implicit , explicit operators page:

that's correct. defining implicit operator allows explicit conversion. defining explicit operator allows explicit conversion.

thus, if define explicit operator, can following:

thing thing = (thing)"value";

if define implicit operator, can still above, can take advantage of implicit conversion:

thing thing = "value";

so in short, explicit allows explicit conversion, while implicit allows both explicit , implicit... hence reason can define one.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -