Search code examples
c#tuplesnew-operator

What is the meaning of the new operator when creating a modern tuple? Or is it a rudiment?


Let's say the new operator is left for the modern tuple as a rudiment. That is, it can be ignored.
I can write it when returning a value from a method or property. But I can't write it when declaring a variable.

internal class Program
{
    private static (int, int) getVal1 => (1, 2);
    private static (int, int) getVal2 => new(3, 4);

    private static (int, int) getVal3() { var v = new(5, 6); return v; }
    // Error CS8754 There is no target type ...   ^^^^^^^^^

    static void Main(string[] args)
    {
        Console.WriteLine(getVal1);
        Console.WriteLine(getVal2);
        Console.WriteLine(getVal3());
    }
}

Why is that?


Solution

  • Because in the getVal2 method, the type of the type can be inferred:

    private static (int, int) getVal2 => new(3, 4);
                   ^^^^^^^^^^ type declared as a Tuple
                                            ^^^^^^ must be type (int, int)
    

    Whereas with the statement:

    public record Range(int lower, int upper);
    public record Interval(int start, int end);
    var x = new(5,6);
    ^^^ which type is x? is it a Tuple or a Range or an Interval or something else?
    

    there is no way for the compiler to infer the type. x could be a tuple or any other type which has a parameter which accepts 2 arguments (such as a "Range" or an "Interval" type)