Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use attributes for value tuples

In C# 7.0, .NET introduces a new return value tuple types (functional programming), so instead of:

[NotNull]
WrapperUser Lookup(int id)

I'd like to use value tuples:

(User, Info) Lookup(int id)

And I want to use attributes for these return types:

([NotNull] User, [CanBeNull] Info) Lookup(int id)

But VS2017 doesn't allow me to do it. How can I use attributes without using a wrapper class?

like image 483
MiP Avatar asked Feb 13 '17 07:02

MiP


People also ask

What are value tuples?

ValueTuple is a structure introduced in C# 7.0 which represents the value type Tuple. It is already included in . NET Framework 4.7 or higher version. It allows you to store a data set which contains multiple values that may or may not be related to each other.

Is a tuple an attribute?

A tuple is a sequence of attributes, and an attribute is a named value.

Is tuple value type?

Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types.

When should I use tuple C#?

Tuples can be used in the following scenarios: When you want to return multiple values from a method without using ref or out parameters. When you want to pass multiple values to a method through a single parameter. When you want to hold a database record or some values temporarily without creating a separate class.


1 Answers

You can't.

(User, Info) Lookup(int id)

is just syntactic sugar for

ValueTuple<User,Info> Lookup(int id)

The type parameters of ValueTuple are not valid targets for attributes. Your only option besides a wrapper class is to wrap the type parameters in a NonNullable wrapper

(NonNullable<User>,NonNullable<Info>) Lookup(int id)

which allows you to use it just like a normal ValueTuple, e.g.

(NonNullable<User>,NonNullable<Info>) Lookup(int id) => (new User(), new Info());
(User user, Info info) = Lookup(5);

Otherwise you could stick a custom attribute to the whole ValueTuple indicating which tuple elements can be null with an array, like the TupleElementNamesAttribute that is used to assign names to the tuple elements. You would have to write your own visual studio / resharper plugin that does the work though.

like image 98
RoXX Avatar answered Oct 05 '22 22:10

RoXX