Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason we can't have some syntactic sugar around tuples?

What I would love to see in C# is better syntax around tuples eg.

var rgb = (1.0f, 1.0f, 1.0f);
// Inferred to be Tuple<float, float, float>
// Translated to var rgb = Tuple.Create(1.0f, 1.0f, 1.0f)

And

var x, y, z = rgb;

// Translated to:
//    float x = rgb.Item1;
//    float y = rgb.Item2;
//    float z = rgb.Item3;

Is there anything in the C# language which prohibits this, or makes it too difficult/unrealistic to achieve? Perhaps there are other language features which would directly clash with this?

Note that I'm not asking if this is on Microsofts radar or even if it aligns with their vision for C#, just if there are any obvious blockers to it in theory.

Edit Here are some examples from other CLI languages

// Nemerle - will use a tuple type from a language specific runtime library
def colour = (0.5f, 0.5f, 1.0f);
def (r, g, b) = colour;

// F# - Will use either a library type or `System.Tuple` depending on the framework version.
let colour = (0.5f, 0.5f, 1.0f)
let (r, g, b) = colour

// Boo - uses CLI array
def colour = (0.5, 0.5, 1.0)
def r, g, b = colour

// Cobra - uses CLI array
var colour = (0.5, 0.5, 1.0)
var r, g, b = colour

While using arrays might seem like a good compromise, it becomes limiting when mixing types eg. let a, b = (1, "one") F# or Nemerle will give us a Tuple<int, string>. In Boo or Cobra this would give us an object[].

Edit2 Language support for tuples is added in C# 7 - https://www.kenneth-truyers.net/2016/01/20/new-features-in-c-sharp-7/

like image 291
MattDavey Avatar asked Sep 10 '13 12:09

MattDavey


1 Answers

The second one is not possible, because it already means something else:

float x, y, z = 0.1f;

This declares three variables x, y and z with z being initialized to 0.1. The difference to the syntax proposed in your question is subtle at best.

like image 176
Daniel Hilgarth Avatar answered Sep 28 '22 07:09

Daniel Hilgarth