Compilation error without brackets surrounding the ternary operator when creating Tuples in C #

I found an error in C # with the new Tuple function. If I use the ternary operator to determine the value for a tuple, I must surround it with brackets. I did not expect this, because in method calls this is not so.

Is there a reason for this or is this a mistake?

Setup:

  • Visual studio 2017
  • .Net Standard 1.6 Class Library
  • System.ValueTuple (v4.3.0 - from Nuget)

My code is:

public class Test { public bool Ok { get; set; } public string Text { get; set; } } public class Class1 { public void TestMethod() { // // FROM OBJECT // Test obj = new Test() { Ok = true, Text = "asdf" }; StringMethod(true, obj.Ok ? obj.Text : "fsda"); // <-- OK var result1 = (true, obj.Ok ? obj.Text : "fsda"); // <-- Error var result2 = (true, (obj.Ok ? obj.Text : "fsda")); // <-- OK (Same as line above, but with addional brackets) // // FROM OTHER TUPLE // var tuple = OtherTuple(); StringMethod(true, tuple.ok ? tuple.text : "fdsa"); // <-- OK var result3 = (true, tuple.ok ? tuple.text : "fdsa"); // <-- Error var result4 = (true, (tuple.ok ? tuple.text : "fdsa")); // <-- OK (Same as line above, but with addional brackets) } public void StringMethod(bool state, string anyString) { } public (bool ok, string text) OtherTuple() { return (true, "asdf"); } } 
+8
c # ternary-operator tuples
source share
1 answer

I think var cannot determine that you are trying to set the Tuple value in this line

  var result3 = (true, tuple.ok ? tuple.text : "fdsa"); 

Perhaps if you are more clear:

  var result3 = Tuple.Create(true, tuple.ok ? tuple.text : "fdsa"); 

This makes it easier to read code.

-3
source share

All Articles