How to use Tuple in generic class?
So I know you can use Tuple<Type, Func<object>> for example, but is there any way to just use (Type type, Func<Object> obj)? Or even give Tuple<> names so it isn't Item1, Item2?
I imagine if this isn't implemented it has to do with how the () tuple works at compile, but I would think it is easy enough on compile time to just do .ToTuple() wherever it would be needed.
20 Replies
You should typically avoid
Tuple<...>
as it's the old reference type. Use ValueTuple<...>
with the newer syntax.
eg. (Type Type, Func<object> Function) tuple = (typeof(Program), () => 5);
Unfortunately, I don't think you can use var
here and name the right-hand side.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples#tuple-field-names
You could otherwise in tuples that don't have lambdas.You get this error if you try only the RHS.
there is a tuple notation in C# that you can use, but that is not Tuple<>, it's actually ValueTuple<> (which for our purposes should do the same thing)
and you can actually use var and name elements from the RHS
(Type: a, Function: b)
Not sure how to do that with Generic.
For example
Is what I am getting with ValueType, but if I put (itn: age, string: name) it throws errors.
well what is the actual code that shows error and what error
throws
I would use a concrete type there, not a tuple.
Especially in Unity where C# is weaker.
is for
It's because
ValueTuple<int, string>
is not quite the same as (int value, string name)
so you need to write
Ah yep that is working now. Not sure where I was bonking it up yesterday 😆
I think it's really just complaining why you don't have names matched up yeah
I am working in unity so maybe the (int: age, string: name) is a newer C# way? the (int age, string name) works fine.
no it's like two different things
I think I understood your question as 'how to name tuple elements on construction using var' in which case you can do
var a = (Name: "hello", Age: 20);
i don't think
(int: arg, string: name)
is valid for a declaration, and even if it was var t = (int: age, string: name)
where age and name already exists, int and strings are keywords so it wouldn't workCool cool, thanks for the help!
also Klarth's point is valid, tuples can be fine for some one-off stuffs but they get kinda long and cumbersome (somewhat) if you end up using it a lot
records could be an alternative
i mean if they're using unity, they probably don't have records :/
oh crap
runs
ye unity isn't great lol
Yeah I am using it for some generic stuff that doesn't need a full command struct for the args, but need different number of args per inheritor.