Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

c# - Math operations with null

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...