I am trying to use the Null-conditional Operator (?) but I am not quite sure where exactly to put it separators.Contains(textLine[(index - 1)]). I want to say "If (textLine[(index - 1)]) isn't null proceed". Some help?
3 Answers
This is not the way Null-conditional Operators works.
Null-conditional Operators, only returns null instead of an exception, if one of the parents marked with prefix of ? is == null
Example:
var g1 = parent?.child?.child?.child;
if (g1 != null) // TODO
What you need, is a simple IF condition
if (!string.IsNullOrEmpty(textLine))
{
// Work here
}
Comments
If you mean to not call the contains method if the value in your array is null then you have to check it first.
// requires possible bounds checking
char? test = textLine?[index-1];
if (test != null && separaters.Contains(test.Value))
Using linq:
// does not require bounds checking
char test = textLine?.Skip(index-1).FirstOrDefault() ?? default(char);
if (test != default(char) && separaters.Contains(test))
10 Comments
M.kazem Akhgary
first of all char can never be null. did you mean to write
textLine?[index-1]; instead?user7388546
yea that's what i realised now @M.kazemAkhgary
Rabid Penguin
That's correct i was unsure if he meant textLine would be null or the value in the array could be null
user7388546
I am getting an out of range exception
Rabid Penguin
You could use linq. char test = textLine?.Skip(index-1).FirstOrDefault() ?? default(char). Then test against default(char)
|
The second example of the MSDN Docs should answer your question:
Customer first = customers?[0]; // null if customers is null
if-statement.if)