views:

38

answers:

1

This might sound crazy to you, but I need a Nullable<T> (where T is a struct) to return a different type for it's Value property.

Rules being if Nullable<T>'s Property HasValue is true, Value will always return an object of a different specified type (then itself).

I might be over thinking this, but this unit test bellow kind of shows what I want to do.

    public struct Bob
    {
            ...
    }


    [TestClass]
    public class BobTest
    {
            [TestMethod]
            public void Test_Nullable_Bob_Returns_Joe()
            {
                    Joe joe = null;
                    Bob? bob;
                    var bobHasValue = bob.HasValue; // returns if Bob is null

                    if(bobHasValue)
                            joe = bob.Value; //Bob returns a Joe
            }
    }
+3  A: 

Are you look for a user-defined implicit conversion? If so, you can define one on Bob:

class Bob {
    static public implicit operator Joe(Bob theBob) {
       // return whatever here...
    }
}

If you can't do this because you don't have access to change Bob, you could always consider writing an extension method:

public static class BobExt {
    public static Joe ToJoe( this Bob theBob ) {
        return whatever; // your logic here...
    }
}

if(bobHasValue) 
    joe = bob.Value.ToJoe(); // Bob converted to a Joe
LBushkin
Nice one! Don't you want an `implicit` though?
Kobi
@Kobi: Haha. I need to cut back on the coffee. Yes, thank you - I fixed my example.
LBushkin
If I remember correctly, the conversion operator is not required to be defined within the class.
Zach Johnson
@Zach Johnson: I don't this so. Take a look at this: http://msdn.microsoft.com/en-us/library/2x7fay24(VS.80).aspx
LBushkin
@LBushkin: Oops! Yes, you are correct. I sure thought I remembered doing it at one point, but I guess not...
Zach Johnson
I think implicit conversion could work well in what I am trying to accomplish, thank you.
Andrew