Background and motivation
Some code needs to throw NullReferenceException instead of ArgumentNullException, either for performance or compatibility reasons.
Currently the code relies on using weird patterns to trigger that, which is both not nice to write and obscures the intent of code, introducing need for comments.
Introducing an explicit way to trigger a nullcheck would make the code clearer to any reader.
The check would be implemented using a dereference by runtime, so invalid pointers would cause an AccessViolationException.
API Proposal
namespace System;
public class NullReferenceException
{
public static void ThrowIfNull(object i);
public static void ThrowIfNull(void* ptr);
public static void ThrowIfNull<T>(ref readonly T r);
}
API Usage
NullReferenceException.ThrowIfNull(obj);
NullReferenceException.ThrowIfNull(ptr);
NullReferenceException.ThrowIfNull(ref r);
Alternative Designs
People can continue doing the obscure current variants:
_ = obj.field; // needs to know the type
_ = Unsafe.ReadUnaligned<byte>(ptr); // Null pointers are UB in C#.
_ = Unsafe.ReadUnaligned<byte>(ref Unsafe.As<T, byte>(ref r)); // Roslyn optimizes out unused derefs.
Risks
No response
Background and motivation
Some code needs to throw
NullReferenceExceptioninstead ofArgumentNullException, either for performance or compatibility reasons.Currently the code relies on using weird patterns to trigger that, which is both not nice to write and obscures the intent of code, introducing need for comments.
Introducing an explicit way to trigger a nullcheck would make the code clearer to any reader.
The check would be implemented using a dereference by runtime, so invalid pointers would cause an
AccessViolationException.API Proposal
API Usage
Alternative Designs
People can continue doing the obscure current variants:
Risks
No response