-5

I found a piece of code online where there is this line:

new Claim(JwtClaimTypes.EmailVerified, 
     user.EmailConfirmed ? "true" : "false",
     ClaimValueTypes.Boolean)

While the code works I'm not sure what does that specific line do. I know the "?" symbol is used to nullify Types, but can it be used to cast Types as well?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 4
    That's a ternary operator and is entirely different from the `?` the symbolizes a nullable value. This operator is only available for boolean values and the `?` signifies what to do if the boolean value is true. `:` means otherwise. – jegtugado Oct 23 '17 at 01:10
  • 2
    Reference: [conditional operator](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator) – Jonathan Lonowski Oct 23 '17 at 01:11

1 Answers1

3

It is not for casting. It is just the conditional operator, an easy syntax to do an if-else code block. So if the expression before ? returns true, it executes the first expression ( the one followed by ?) and return the value and if the expression before ? returns false, it returns the return value of the second expression (followed by :)

So in your case, If the value of the expression user.EmailConfirmed is true the code will be same as

new Claim(JwtClaimTypes.EmailVerified,  "true" , ClaimValueTypes.Boolean)

else (if it is false)

new Claim(JwtClaimTypes.EmailVerified,  "false" , ClaimValueTypes.Boolean)

You can also call the ToString() method on the boolean value and then call ToLower() method to get true or false . If you ever want to try that, Here is how you do it

new Claim(JwtClaimTypes.EmailVerified, user.EmailConfirmed.ToString().ToLower(),
                                                                ClaimValueTypes.Boolean)

I would personally prefer the first approach ( conditional operator), but probably replace the magic strings with some constants

Shyju
  • 214,206
  • 104
  • 411
  • 497