views:

91

answers:

3

For example implicitly

MyClass myClass = new MyClass();
int i = myClass;
+7  A: 

You need to define this in the MyClass file.

public static implicit operator int(MyClass instance) 
{
    if (instance == null) 
    {
        return -1;
    }
    return instance._underlyingValue;
}
ChaosPandion
Should it perhaps be an `int?` implicit conversion so there doesn't need to be a magic value? Particularly if -1 could be a legitimate underlying value. I would think for situations like this you would either want to return null if the conversion isn't possible or throw an exception. (Obviously your answer fits the spec, so this is more of a questioning of the spec rather than the answer.)
Anthony Pegram
@Anthony - In principle, I agree with you. In practice it is highly dependent on the class in question.
ChaosPandion
+4  A: 
class MyClass 
{
   public static implicit operator int(MyClass myClass) 
   {
      // code to convert from MyClass to int
   }
}

Take a look there : implicit

Patrice Pezillier
+2  A: 

This MSDN entry covers what you want exactly, should do the trick.

Matt Greer