Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Please explain why this test passes?

[Test]
public void TestNullOps()
{
    Assert.That(10 / null, Is.Null);
    Assert.That(10 * null, Is.Null);
    Assert.That(10 + null, Is.Null);
    Assert.That(10 - null, Is.Null);
    Assert.That(10 % null, Is.Null);
    Assert.That(null / 10, Is.Null);
    Assert.That(null * 10, Is.Null);
    Assert.That(null + 10, Is.Null);
    Assert.That(null - 10, Is.Null);
    Assert.That(null % 10, Is.Null);

    int zero = 0;
    Assert.That(null / zero, Is.Null);
}

I don't understand how this code even compiles.

Looks like each math expression with null returns Nullable<T> (e.g. 10 / null is a Nullable<int>). But I don't see operator methods in Nullable<T> class. If these operators are taken from int, why the last assertion doesn't fail?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
349 views
Welcome To Ask or Share your Answers For Others

1 Answer

From MSDN:

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result.

That's why all the test are passed, including the last one - no matter what the operand value is, if another operand is null, then the result is null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...