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";
}
Well, the problem is in the execution order:
"somestring " + B(will be"something " + null == "something ")"somestring " is not null(true, since"something "is not null)$" {B.Property}"- exception is thrown sinceBisnullLet's add parenthesis to show the actual order:
In the second version
we have a different order
(B is not null ? $" {B.Property}" : "empty")-"empty", sinceBisnull."somestring " + "empty" == "something empty"