0

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?

9
  • Do you mean "if the expression is not null, call the Contains method, otherwise don't"? Commented Jan 7, 2017 at 18:08
  • ..............yes Commented Jan 7, 2017 at 18:10
  • And how should your program act in else case? Commented Jan 7, 2017 at 18:10
  • 1
    Unfortunately this can't be done, you need to use an if-statement. Commented Jan 7, 2017 at 18:11
  • 2
    operators are for expressions, flow of control are for statements. You need flow of control (eg if) Commented Jan 7, 2017 at 18:12

3 Answers 3

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

first of all char can never be null. did you mean to write textLine?[index-1]; instead?
yea that's what i realised now @M.kazemAkhgary
That's correct i was unsure if he meant textLine would be null or the value in the array could be null
I am getting an out of range exception
You could use linq. char test = textLine?.Skip(index-1).FirstOrDefault() ?? default(char). Then test against default(char)
|
1

The second example of the MSDN Docs should answer your question:

 Customer first = customers?[0];  // null if customers is null  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.