Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add additional property to tuple c# 7

Tags:

c#

tuples

c#-7.0

Had a search and can't find anything on this so I'm thinking it may not be possible at present.

Given the following two tuples

var a = (a: "1", b: 2);
var b = (c: "2", d: 0.1);

Is it possible for me to dynamically compose/merge these objects into one

var c = a + b;

Ideally the names of the properties are maintained so we can still do the following

var d = c.b + c.d;

I'm aware I could do the following but this won't work for what I want to achieve

var c = (first:a, second:b);

I'm looking for a general solution, i.e. I don't care how many properties are in each tuple.

Furthermore I'm aware that there could be issues such as what happens if there are two properties with the same name. In such a scenario I'm happy for the property to be overwritten or the name to be altered so it became a_1 for example.

like image 775
jps Avatar asked Oct 21 '25 16:10

jps


1 Answers

From the way you describe your use case, you need to know both the name of the field and its value. C# 7's tuples aren't therefore going to be of help here:

  1. Those tuples just map to ValueTuple<,>, ValueTuple<,,> etc, ie a tuple with two fields and a tuple with three are completely different types.
  2. The field names are just compiler trickery. They exist as metadata for the compiler, but are not accessible at runtime, eg via reflection.

What you need are key/value pairs and sets of them that can be merged into new sets. Therefore the type that seems to best fit your needs would be Dictionary<string,object>.

like image 136
David Arno Avatar answered Oct 23 '25 07:10

David Arno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!