Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math operations with null

Tags:

c#

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?

like image 830
altso Avatar asked Oct 05 '11 11:10

altso


People also ask

What is null in math?

In mathematical sets, the null set, also called the empty set, is the set that does not contain anything. It is symbolized or { }. There is only one null set. This is because there is logically only one way that a set can contain nothing.

What are the two operators for dealing with null values?

To handle NULLs correctly, SQL provides two special comparison operators: IS NULL and IS NOT NULL.

What is null give example?

A null value indicates a lack of a value, which is not the same thing as a value of zero. For example, consider the question "How many books does Adam own?" The answer may be "zero" (we know that he owns none) or "null" (we do not know how many he owns).

When we multiply 0 with null the result is?

An empty product, or nullary product, is the result of multiplying no numbers. Its numerical value is 1 [. . .] So 0⋅0=1.


2 Answers

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.

like image 92
Andrei Avatar answered Sep 25 '22 00:09

Andrei


The operators for Nullable<T> are so-called "lifted" operators]; the c# compiler takes the operators available for T and applies a set of pre-defined rules; for example, with +, the lifted + is null if either operand is null, else the sum of the inner values. Re the last; again, division is defined as null if either operand is null - it never performs the division.

like image 31
Marc Gravell Avatar answered Sep 24 '22 00:09

Marc Gravell