Question

Check if value tuple is default

How to check if a System.ValueTuple is default? Rough example:

(string foo, string bar) MyMethod() => default;

// Later
var result = MyMethod();
if (result is default){ } // doesnt work

I can return a default value in MyMethod using default syntax of C# 7.2. I cannot check for default case back? These are what I tried:

result is default
result == default
result is default(string, string)
result == default(string, string)
 46  26457  46
1 Jan 1970

Solution

 56

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.

2018-04-30

Solution

 13

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 defaultbefore 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:

enter image description here

2018-04-30