2

With C# 7 being implemented, Tuples got a LOT easier to use. In fact, I have a case where I'll be using an identical Tuple signature for a few methods.

To save on typing, can I name or alias it? Or should I just go ahead and define a struct?

Djensen
  • 1,337
  • 1
  • 22
  • 32
  • 4
    Possible duplicate of [In C# can you define an alias to a value tuple with names?](http://stackoverflow.com/questions/43181070/in-c-sharp-can-you-define-an-alias-to-a-value-tuple-with-names) – cremor Apr 26 '17 at 10:45
  • You can't alias the *names* for now, as they are just compiler magic, not part of the type. The duplicate explains that this is will be available with records, which were moved to C# 8 – Panagiotis Kanavos Apr 27 '17 at 09:32

3 Answers3

3

You can use alias with value tuples like with any other type:

> using T = System.ValueTuple<int, string>;    
> T t;
> t.Item1 = 1;
> t.Item2 = "one";

But that's probably not what you're looking for. And that's because the tuple value names are not in the type itself but in the variables and return values.

In the case of variables, the compiler keeps track of the value names. In the case of return values, the [System.Runtime.CompilerServices.TupleElementNamesAttribute] attribute is used to attach the names to the return value.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59
2

No you can not make a alias. If you want some kind of "short form" you will need to define an actual type and use that instead of the tuple.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
2

Having read more of the existing duplicates, there's an important point which I think should be mentioned: Tuples in C# 7 are syntactic sugar, making Structs easier to use as one-offs.

That being the case, if a particular structure of tuple is going to be reused enough to need a name, then the full Struct syntax would be the appropriate solution.

  • In my case, it's only being used once in one class file, however `(TileColor, TileComponents)` is a bit more combersome to type over and over again than `TileSide` is. – AustinWBryan Aug 07 '19 at 08:35