+ 2
What is this syntax in C#?
Working on some legacy C# code, I came across expression syntax like this: (myString.ToUpper()?.ToString()) What does it do?
5 Answers
+ 7
Could be a null-conditional operator? I have never used it either.
https://stackoverflow.com/questions/43075113/what-does-a-question-mark-mean-in-c-sharp-code
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-
+ 3
Thank you Lisa and Justice. I learned several new things about C# from the articles that Lisa linked. Humble appreciation!
Now I understand the ?. operator, but I still don't grok the result of the expression. Suppose myString is non-null. It transforms the string to uppercase and then converts that string into ... a string?? š¶
+ 2
Lisa Yup! Tbh, it's much more of a backend thing to make sure that you're not getting the equivalent of a NullException which can be known as the Billion Dollar Mistake. Java has terrible null safety but languages like C# and Kotlin try to combat it with that specific syntax.
+ 1
Looks like it taking a value, converting it into all uppercase and then converting into a string. The ? for most languages means that it's just checking if it's null.
+ 1
Well folks, upon further review of the legacy code, I have concluded that someone simply did a massive find/replace, and did not check whether the code made sense still afterward.