Check if value tuple is default
As of C# 7.3, tuple types now support == and !=. So your code could look like this:
(string foo, string bar) MyMethod() => default;
// Later
var result = MyMethod();
if (result == default){ } // Works!
See https://docs.microsoft.com/en-us/dotnet/csharp/tuples#equality-and-tuples
There are two problems with your attempts:
- There is no
==
operator defined on tuples (in C# 7.2) - To get a default value for a tuple type, you need to parenthesize the type properly:
default((int, int))
Note that an ==
operator is added to tuples in C# 7.3. Then you can do tuple == default
(see live example).
If you really want to keep it returning default
, you could use
result.Equals(default)
the built-in Equals
method of a ValueTuple
should work.
As of C# 7.3 value tuples now also support comparisons via ==
and !=
fully,
Meaning you can now also do
result == default
and it should work the same.
There are several ways of comparing default values to a value tuple:
[TestMethod]
public void Default()
{
(string foo, string bar) MyMethod() => default;
(string, string) x = default;
var result = MyMethod();
// These from your answer are not compilable
// Assert.IsFalse(x == default);
// Assert.IsFalse(x == default(string string));
// Assert.IsFalse(x is default);
// Assert.IsFalse(x is default(string string));
Assert.IsFalse(Equals(x, default));
Assert.IsFalse(Equals(result, default));
Assert.IsTrue(Equals(x, default((string, string))));
Assert.IsTrue(Equals(result, default((string, string))));
Assert.IsTrue(result.Equals(default));
Assert.IsTrue(x.Equals(default));
Assert.IsTrue(result.Equals(default((string, string))));
x.Equals(default((string, string)))
}
A simple default
before it's used in a comparison must be reified from its "pure" null
to a value tuple with default values for the members.
Here's what I have under the debugger: