c# 7.0 tuple used as custom type

Viewed 523

I have a C# 7.0 tuple declaration, for example:

(int ID, string name, string secondName, int age) foo = (19,"Harry", "Potter", 8);

Each time a declare a new var or if I use it in a function/method, I need to rewrite the whole declaration. For example:

private (int ID, string name, string secondName, int age) DoSomething((int ID, string name, string secondName, int age) passedElement) {...

I'd like to use it as a custom type and write something like this:

private MyType DoSomething(MyType passedElement) {...

With conventional tuples I always use:

using MyType = System.Tuple< int, string, string, int>;

It works fine, but if I try to use:

using MyType = (int ID, string name, string secondName, int age);

intellisense gives me an error "identifier expected" underlining the part on the right of equal sign.

What's the right way to declare it, if there is one?

Thank you in advance.

1 Answers

Tuples are not types. Not in the usual sense.

Tuples in C# were created to act as a bag of individual values.

The specified tuple element names are not part of the type but annotations on the instances created from that definition. For the runtime (and the compiler, for the most part), (int ID, string name, string secondName, int age) it's the same as (int i1, string s1, string s2, int i2) or (int, string, string, int).

Related