A way to get the value that is used in a ternary operator without creating a new variable #4877
Replies: 3 comments 20 replies
-
What you're looking for isn't just the value of the ternary, you're asking for the left-hand side of an expression inside the ternary, which is much more complex and not something we can really generally purpose in C#. You could do something like this, but it's not elegant: var random = new Random();
Console.WriteLine(random.Next is var nextInt && (nextInt % 0 is 0) ? $"The number {nextInt} is an even number" : $"The number {nextInt} is an odd number"); I honestly wouldn't recommend this though: your first example is much clearer. |
Beta Was this translation helpful? Give feedback.
-
var random = new Random();
Console.WriteLine((defer random.Next()) % 2 == 0 ? $"The number {it} is an even number" : $"The number {it} is an odd number"); |
Beta Was this translation helpful? Give feedback.
-
I would say that using a variable is necessary. If you are defining much more variables, you should consider creating a helper method. And for this specific case, |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Usually when we use a ternary operator, we want to return the value that was evaluated, and we usually create a variable that already stores this value, and using a variable to store a temporary value is unnecessary (at least in my view), so mine proposal is to create a keyword that takes the value that was analyzed in the ternary operator
Generally, we would do it like this:
What I want to propose is a keyword that prevents us from creating a new variable to store a value that we will compare and probably display later, as was done in the example above, thus saving time
According to what I thought, it would be something +- like:
Don't mind the name
ternaryvalue
, it's just a symbol for what I mean, and also because I couldn't think of a better name, but anyway, it's pretty simple, ifrandom.Next()
generates any value, like 4318, instead of storing this value in another variable, the keywordternaryvalue
takes the value 4318 and displays it on the screen normallyI believe I have not been clear enough, any questions, just ask
Beta Was this translation helpful? Give feedback.
All reactions