I discovered the strange behavior of my program, and after further analysis, I was able to find that there is probably something wrong both in my knowledge of C # and elsewhere. I believe that this is my mistake, but I can not find the answer anywhere ...
public class B { public static implicit operator B(A values) { return null; } } public class A { } public class Program { static void Main(string[] args) { A a = new A(); B b = a ?? new B();
The variable "b" in this code evaluates to null. I do not understand why this is null.
I googled and found the answer in this question - Implicit casting of the result of the Null-Coalescing operator - with the official specification.
But after this specification, I canβt find the reason why βbβ is null :( Maybe I am reading this incorrectly, in which case I apologize for the spam.
If A exists and is not a NULL or reference type, a compile-time error occurs.
... this is not the case.
If b is a dynamic expression, the type of the result is dynamic. At runtime, a is first evaluated. If a is not null, a is converted to dynamic, and this becomes the result. Otherwise, b is evaluated, and this becomes the result.
... this is not the case either.
Otherwise, if A exists and is of type NULL, and there is an implicit conversion from b to A0, then the result is A0. At runtime, a is first evaluated. If a is not null, a is expanded to enter A0, and this becomes the result. Otherwise, b is evaluated and converted to type A0, and this becomes the result.
... A exists, an implicit conversion from b to A0 does not exist.
Otherwise, if A exists and there is an implicit conversion from b to A, then the result is A. At run time, a is first evaluated. If a is not null, a becomes the result. Otherwise, b is evaluated and converted to type A, and this becomes the result.
... A exists, the implicit conversion from b to does not exist.
Otherwise, if b is of type B and there is an implicit conversion from a to B, then the result is B. At run time, a is first evaluated. If a is not null, a is expanded to enter A0 (if A exists and is NULL) and converted to type B, and this becomes the result. Otherwise, b is evaluated and becomes the result.
... b is of type B and there is an implicit conversion from a to B. a is evaluated as null. Therefore, b must be evaluated and b must be the result.
Otherwise, a and b are incompatible, and a compile-time error occurs. Not happening
Am I missing something?