Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading