Can it returns null? (this.Result ==Result.OK)

c#, null, return

Solution

(this.Result == Result.OK)

OK; let's take this piece by piece:

this.(anything)

That can fail if `this` is `null` - which it never should be, but theoretically can be if you are evil - so we could fail with a `NullReferenceException`.

this.Result

if that is a property accessor (a `get`), then it could fail in any way it likes - it could throw an exception.

Result.OK

now; if this is an `enum`, it is just a `ldc` - but if this `.OK` is actually a static property accessor, it can certainly fail with any exception it likes.

this.Result == Result.OK

We need to know what `.Result` returns; if we assume that it returns a `Result` (we don't know that), then we still need to know what `Result` is: if it is an enum it'll be a direct numeric equality check; if it is a nullable-enum, "lifted" equality rules apply, but still resolve cleanly. If it is a custom type that overloads `==`, then anything could happen and any exception could result.

But here's the crazy: `==` does not need to return a `bool`:

public static int operator ==(int x, Foo foo)
{
    return 0; // DO NOT EVER DO THIS
}
public static int operator !=(int x, Foo foo)
{
    return 0; // DO NOT EVER DO THIS
}

If you the `Result` type is custom, then `(this.Result == Result.OK)` can return anything it wants:

using System;
class P
{
    static void Main()
    {
        new P().Test();
    }
    public Result Result { get; set; }
    public void Test()
    {
        var x = (this.Result == Result.OK);
        Console.WriteLine(x.GetType().Name); // Int32
    }
}
public class Result
{
    public static Result OK { get { return null; } }
    public static int operator ==(Result x, Result y)
    {
        return 42; // DO NOT EVER DO THIS
    }
    public static int operator !=(Result x, Result y)
    {
        return 0; // DO NOT EVER DO THIS
    }
}

Finally, we need to consider that something obscure like a `ThreadAbortException`, `OutOfMemoryException` or `StackOverflowException` could happen at any time.

But in sane conditions: yes, it can only result in a `bool` result.

Problem

Can this code return null? ``` (this.Result == Result.OK) ``` Can this line (or a similar one) return anything except than `true` or `false` (e.g. null)?

Original source