user94028
user94028

Reputation: 5

Avoiding nesting if/else if as well as avoiding InvalidOperationException at the same time in a conditional statement

I encountered this huge method where I have lots of if else statements of the type

else if (ptName == "Missile" ||
         ptName == "Telephone" ||
        (ptName.StartsWith("Car") && gasTank.ValueFloat1.Value < 90))
        {
         foo_1 = "some_string";
        }

Unfortunately this code is not completely correct since the variable gasTank is only defined by cases where ptName starts with the string "Car". Thus, during runtime I get the

InvalidOperationException occured: Null object must have a value.

This could be solved by nesting ifs and else ifs, as well as repeating the condition ptName.StartsWith("Car"), although it is highly undesirable.

Splitting the method into many little ones or adding return after each condition is not an option, since the method's return is a concatenation of various foo_i.

Thank you in advance.

Upvotes: 0

Views: 57

Answers (1)

Michał Turczyn
Michał Turczyn

Reputation: 37375

Condition

ptName.StartsWith("Car")

should become

ptName?.StartsWith("Car") ?? false

That would spare you from null value.

If you are using C# version below 6, then you should use:

ptNAme == null ? false : ptName.StartsWith("Car")

Another update:

(gasTank.ValueFloat1?.Value ?? 0) < 90

or

(gasTank.ValueFloat1.HasValue ? gasTank.ValueFloat1.Value : 0) < 90

Upvotes: 4

Related Questions