Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Concatenate String and Is Operator

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";
 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading