-3

Is it safe to use the . operator after using the null-conditional operator ?. ?

string x = MaybeReturnsNullMethod();
string y = x?.Substring(2).PadRight(1);

I thought the correct code on line 2 to avoid a possible NullReferenceException would be

string y = x?.Substring(2)?.PadRight(1);
Elliott Beach
  • 10,459
  • 9
  • 28
  • 41
  • Side note: "For example, why does the below code print True" - you completely missed that part of the code... (not that adding that would make question much better, but probably would have saved from some votes)… Also it is good idea to [RTFM](https://learn.microsoft.com/en-us/dotnet/api/system.string.substring?redirectedfrom=MSDN&view=netframework-4.8#System_String_Substring_System_Int32_System_Int32_) before picking functions for your example code - `string.Substring` never returns `null`... – Alexei Levenkov Apr 26 '19 at 00:04
  • Sorry, I should have proofread. However, the criticism that `string.Substring` never returns null is irrelevant. In fact, the code is extracted from the blog post linked to in my answer. – Elliott Beach Apr 26 '19 at 00:06
  • After re-reading question couple times `Substring` sort of makes the point about potential need for second question mark and aligns to what you tried to pose as the question... I would not ask that after reading MSDN [?. and ?\[\] null-conditional operators](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operators): "The null-conditional operators are short-circuiting. If one operation in a chain of conditional member access and index operations returns null, the rest of the chain’s execution stops." - but maybe someone will find the post useful... – Alexei Levenkov Apr 26 '19 at 00:22

1 Answers1

0

The expresssion x?.SomeMethod().ToString() will return null when x is null. This is due to a C# behavior called null propogation.

Even though Substring is called via the null-conditional operator, and a null value?.Substring could seemingly return null, the language behavior does what you would want. It short-circuits the call and immediately returns null, avoiding the programming error that would otherwise result in a NullReferenceException. This is a concept known as null-propagation.

It just works.

Elliott Beach
  • 10,459
  • 9
  • 28
  • 41