As others have said, it will only work when T is constrained to be a reference type. Without any constraints, you can compare with null, but only null - and that comparison will always be false for non-nullable value types.
Instead of calling Equals, it's better to use an IComparer<T>
- and if you have no more information, EqualityComparer<T>.Default
is a good choice:
public bool Compare<T>(T x, T y)
{
return EqualityComparer<T>.Default.Equals(x, y);
}
Aside from anything else, this avoids boxing/casting.
Update
JavaScript now supports the nullish coalescing operator (??). It returns its right-hand-side operand when its left-hand-side operand is null
or undefined
, and otherwise returns its left-hand-side operand.
Please check compatibility before using it.
The JavaScript equivalent of the C# null coalescing operator (??
) is using a logical OR (||
):
var whatIWant = someString || "Cookies!";
There are cases (clarified below) that the behaviour won't match that of C#, but this is the general, terse way of assigning default/alternative values in JavaScript.
Clarification
Regardless of the type of the first operand, if casting it to a Boolean results in false
, the assignment will use the second operand. Beware of all the cases below:
alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
This means:
var whatIWant = null || new ShinyObject(); // is a new shiny object
var whatIWant = undefined || "well defined"; // is "well defined"
var whatIWant = 0 || 42; // is 42
var whatIWant = "" || "a million bucks"; // is "a million bucks"
var whatIWant = "false" || "no way"; // is "false"
Best Answer
Comparing the lists with
==
requires elements to be comparable (denoted asEq a
).For example,
[sin] == []
won't work, since you can't compare functions. It might seem stupid, but the type system must judge type of an expression without looking at its value.An alternate check would be
length xs == 0
, this doesn't require equality but won't stop if your list is infinite (trylength [1..] == 0
). That's why there's a dedicated function.