3 ms·
C# constructors technically don't return anything (afaik), the object is allocated and then the constructor is invoked on it. So it's theoretically possible for
by kevingadd 5y ago
C# constructors technically don't return anything (afaik), the object is allocated and then the constructor is invoked on it. So it's theoretically possible for your compiled code to produce a null as the result of a 'new' expression. I think this wouldn't be spec compliant though, since the two scenarios where this would make sense (OOM and exception thrown during alloc or ctor) should just throw and unwind before you can see observe the null or uninitialized instance.
FWIW, it's also possible to enter an instance method with a null 'this' under certain circumstances (normally there would be a null reference check before entering the method body, but I've run into cases where there wasn't)
Contrived scenario: You AOT-compile your code in a 'no exceptions' mode, so the generated code assumes that malloc can't throw, etc. In that case if a failure happens during the 'new' process the only reasonable return values are either null or an instance with garbage data in it. As a compiler author, out of the two I'd probably pick null. This isn't as far-fetched as it sounds since right now exception handling in WebAssembly is a nightmare.
Actually, I wonder if an exception filter could observe the null before the unwind happens...