This statement seems to work, but I'm not sure exactly how
int id = 0; // non-nullable ("primative"/value-type/struct)
_list?.Find(t => { return t?.Id == id; })?.DeptId ?? 0;
If t
is null
, then t?.Id
is null
, correct?
Then how is this legal:
null == id
Update (5/8/18)
The statement in visual studio
if (null == 0) {}
Gets highlighted green and upon inspection with a mouse over states
"The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'
Update (5/24/18)
Nullable
<T>
StructFundamental Properties
The two fundamental members of the Nullable structure are the HasValue and Value properties. If the HasValue property for a Nullable object is true, the value of the object can be accessed with the Value property. If the HasValue property is false, the value of the object is undefined and an attempt to access the Value property throws an InvalidOperationException.
Boxing and Unboxing
When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself. That is, if the HasValue property is true, the contents of the Value property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new Nullable structure initialized to the underlying value.
If the HasValue property of a nullable type is false, the result of a boxing operation is null. Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is null. When null is unboxed into a nullable type, the common language runtime creates a new Nullable structure and initializes its HasValue property to false.
ref: https://learn.microsoft.com/en-us/dotnet/api/system.nullable-1?view=netframework-4.7.2