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 is not null ? $" {B.Property}" : "empty
"somestring " + B
(will be "something " + null == "something "
)"somestring " is not null
(true
, since "something "
is not null)$" {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
(B is not null ? $" {B.Property}" : "empty")
- "empty"
, since B
is null
."somestring " + "empty" == "something empty"