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?
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.
A tuple is a sequence of attributes, and an attribute is a named value.
Tuple types are value types; tuple elements are public fields. That makes tuples mutable value types.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With