Explicit casting to uint when there is no such operator
<p>I have written a simple wrapper around a <code>ulong</code> with a private data member. I want to be able to cast the wrapper to <code>ulong</code> to retrieve the data. I want it to be illegal to cast to <code>uint</code> and lose data, so I did not write an explicit cast to <code>uint</code>. You can imagine my surprise when C# allowed me to cast to <code>uint</code> without complaint and did not throw an exception even though the high bits were lost. </p>

<p>Here is my test code:</p>

<pre><code>class Program {
    static void Main(string[] args) {
        ULongWrapper a = new ULongWrapper(0xfffffffffUL);
        ulong b = (ulong)a;
        uint c = (uint)a;
        Console.WriteLine("{0:x}", b);
        Console.WriteLine("{0:x}", c);
    }
}
class ULongWrapper {
    private ulong data;
    public ULongWrapper(ulong data) {
        this.data = data;
    }
    public static explicit operator ulong(ULongWrapper x) {
        return x.data;
    }
}
</code></pre>

<p>Which prints:</p>

<pre><code>fffffffff
ffffffff
</code></pre>

<p>This seems like unwanted behavior, since I want casts to <code>uint</code> to fail at compile time! The compiler is using the <code>ulong</code> explicit cast operator and then somehow implicitly casting that result to a <code>uint</code> without bounds checking. Is this a bug in C#, and if not, why?</p>
