Concatenate String and Is Operator

73 views Asked by At

I do not understand why this code does throw a nullref. I think it has something to do with the priority of the 'plus' operator and the 'is' operator but I am really not sure why.

 return "somestring " + B is not null  ? $" {B.Property}" : "empty";

Full sample:

internal class Program
 {
     static void Main(string[] args)
     {
         var a = new A();
         Console.WriteLine(a.ToString());
         Console.ReadKey();
     }
 }

 public class A
 {
     public B? B  { get; set; }

     public override string ToString()
     {
         return "somestring " + B is not null  ? $" {B.Property}" : "empty"; //nullref 
         return "somestring " + (B is not null ? $" {B.Property}" : "empty"); //works
     }
 }

 public class B
 {
     public string Property { get; set; } = "Property";
 }
1

There are 1 answers

1
Dmitry Bychenko On BEST ANSWER

Well, the problem is in the execution order:

"somestring " + B is not null  ? $" {B.Property}" : "empty
  1. "somestring " + B (will be "something " + null == "something ")
  2. "somestring " is not null (true, since "something " is not null)
  3. $" {B.Property}" - exception is thrown since B is null

Let's add parenthesis to show the actual order:

(("somestring " + B) is not null) ? $" {B.Property}" : "empty

In the second version

"somestring " + (B is not null ? $" {B.Property}" : "empty")

we have a different order

  1. (B is not null ? $" {B.Property}" : "empty") - "empty", since B is null.
  2. "somestring " + "empty" == "something empty"