Why does calling an Action, that is null, throw NullReferenceException? - c#

Why do I have to check if an Action is not null to avoid getting a NullReferenceException? Isn't it logical if there is no action, then it's okay to just do nothing and proceed? I don't understand why it has to throw an exception. Action is a class, why doesn't it handle this itself?

You're trying to invoke an instance method (Invoke) on an object. Doing that always fails with a NullReferenceException if you're using a null reference1. For example:
object x = null;
string y = x.ToString();
Should object.ToString() handle that too?
Basically, this is consistent with the way the rest of the type system works. The C# language could have been designed in a different way - potentially only for the "shorthand" of action() meaning action.Invoke() - but it wasn't, and it's not going to change now.
It's easy enough to add your own extension method to Action if you want to:
public static class ActionExtensions
{
public static void NullSafeInvoke(this Action action)
{
if (action != null)
{
action();
}
}
}
Or use the C# 6 null-conditional operator to only invoke the delegate when the reference is non-null:
myAction?.Invoke();
(This works for any delegate type, not just actions - for EventHandler for example, you'd use something like handler?.Invoke(this, new EventArgs()). The EventArgs() constructor won't even be called if handler is null.)
1 At least using C#. There are ways of invoking instance methods non-virtually "on" null references in IL, but it's far from the normal.

Since C# 6.0 you can:
myAction?.Invoke();
No extension methods needed.

Action is a delegate, not a class. When you invoke an action, like so:
myAction();
What really is happening here is this:
myAction.Invoke();
If myAction is null you are calling Invoke on a null instance, which is what naturally raises a NullReferenceException.

Related

C# generic implicit operator return type

For purposes of automatically translating code from C++ to C#, I would like to have a C# class (psuedo-code)
class Null {
public static implicit operator T (Null unused) {
return null;
}
}
This would be useful in cases such as
foo(T1 x) { ... }
foo(T2 x) { ... }
foo(null); // ambiguous
For certain reasons, programmatically disambiguating the above type is not in general possible. E.g.
foo((T1)null); // Discovering T1 over T2 is not possible or really hard to do
But if I had the Null class above, I could programmatically add in
foo(Null x) {...}
and generate
foo(new Null()); // not ambiguous
The trick would be to use new Null() in place of every generated null such that even
T1 x = new Null();
compiles with x == null.
Is it possible to write such a class?
No. Absent the dynamic keyword, all method binding in C# is done at compile-time--even binding to implicit cast operators. That means that the problem you're running into with method overload resolution will also prevent the compiler from being able to figure out whether you want your null to be implicitly cast to a T1 or a T2. And using dynamic won't work, because null doesn't have any type at runtime.
It is possible that there are other solutions to your problem if you can share more information. For example, if either of the two methods would work correctly when passed a null value, and you're just trying to get the generated code to compile, you could create a method like this:
foo(object o) {return Foo((T1)null);}
And then translate calls to:
foo(new object());
The above method would also work if you wanted to use a Null class instead of object--no implicit cast is necessary.
On the other hand, if it does matter which overload gets called with a null value, then you need to tell us how the original program determines which one to call.

Is there a way to have a C# class handle its own null reference exceptions

Question
I'd like to have a class that is able to handle a null reference of itself. How can I do this? Extension methods are the only way I can think to do this but thought I'd ask in case there was some nifty thing I didn't know about C#.
Example
I have a class called User with a property called IsAuthorized.
When User is properly instantiated IsAuthorized has an implementation. However, when my User reference contains null I'd like a call to IsAuthorized to return false instead of exploding.
Solution
Lot's of good answers. I ended up using three of them to solve my problem.
I used the Null Object design pattern suggested by Zaid Masud.
I combined that with Belmiris' suggestion of using struct so I couldn't have a null reference
And got a great explanation for why C# works this way and how I could really solve it from Jon Hanna
Unfortunately I can only pick one of these as my accepted answer so if you are visiting this page you should take the time to up vote all three of these and any of the other excellent answers that were given.
How about a proper Object Oriented solution? This is exactly what the Null Object design pattern is for.
You could extract an IUser interface, have your User object implement this interface, and then create a NullUser object (that also implements IUser) and always returns false on the IsAuthorized property.
Now, modify the consuming code to depend on IUser rather than User. The client code will no longer need a null check.
Code sample below:
public interface IUser
{
// ... other required User method/property signatures
bool IsAuthorized { get; }
}
public class User : IUser
{
// other method/property implementations
public bool IsAuthorized
{
get { // implementation logic here }
}
}
public class NullUser : IUser
{
public bool IsAuthorized
{
get { return false; }
}
}
Now, your code will return an IUser rather than a User and client code will only depend on IUser:
public IUser GetUser()
{
if (condition)
{
return new NullUser(); // never return null anymore, replace with NullUser instead
}
return new User(...);
}
However, when my User reference contains null I'd like IsAuthorized to always return false instead of exploding.
This can only be done if IsAuthorized is a static method, in which case you can check for null. This is why extension methods can do this - they are really just a different syntax for calling a static method.
Calling a method or property, such as IsAuthorized as an instance method requires an instance. Just the act of calling an instance method (including a property getter) on null will trigger the exception. The exception isn't raised by your class, but by the runtime itself when you attempt to use the (null) reference. There is no way around this in C#.
If the variable is null, it means it references no object, therefore is makes no sense (and I think its not technically possible) to handle the null reference inside the class method.
You should guarantee that it is not null, either by checking just before calling "IsAuthorized" or event before.
Edit: Finding an workaround to do that would be a bad thing: it would be confusing for someone to understand the behavior, since it is not the "expected" behavior for the programming language. It could also cause your code to hide some problem (a null value where it should be an object) and create a bug that will be hard to find. That said: it is for sure a bad idea.
The problem isn't with creating such a method at all. It's with calling the method. If you put a test of if(this == null) in your code, that's perfectly valid. I suppose it could be optimised away by the compiler on the basis of it being "impossible" to be hit, but I thankfully it isn't.
However, when you call the method, it'll be done via callvirt, so rather than call the method directly, it will find the version of the method to call for the particular instance just as it would with a virtual method. Since that will fail for null references, your perfectly good self-null-testing method will fail before it is even called.
C# deliberately does this. According to Eric Gunnerson this was because they thought letting you do so would be a bit weird.
I've never understood why letting a .NET language modelled upon C++ do something that is perfectly allowable in both .NET and the C++ compiler produced by the same company,* was considered a bit weird. I've always considered it a bit weird that it wasn't allowed.
You can add something from another language (F# or IL) that calls the class, or use Reflection.Emit to generate a delegate that does so and that'll work fine. For example, the following code will call the version of GetHashCode defined in object (that is, even if GetHashCode was overridden, this doesn't call the override) which is an example of a method that is safe to call on a null instance:
DynamicMethod dynM = new DynamicMethod(string.Empty, typeof(int), new Type[]{typeof(object)}, typeof(object));
ILGenerator ilGen = dynM.GetILGenerator(7);
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Call, typeof(object).GetMethod("GetHashCode"));
ilGen.Emit(OpCodes.Ret);
Func<object, int> RootHashCode = (Func<object, int>)dynM.CreateDelegate(typeof(Func<object, int>));
Console.WriteLine(RootHashCode(null));
The one good thing about this, is that you can hold onto RootHashCode so you only need to build it once (say in a static constructor) and then you can use it repeatedly.
This of course is of no value in letting other code call your method through a null reference, for that extension methods like you suggest are your only bet.
It's also worth noting of course, that if you are writing in a language that doesn't have this quirk of C#, that you should offer some alternative means of getting the "default" result for calling on a null reference because C# people can't get it. Much like C# people should avoid case-only differences between public names because some languages can't deal with that.
Edit: A full example of your question's IsAuthorized being called, since votes suggest some people don't believe it can be done (!)
using System;
using System.Reflection.Emit;
using System.Security;
/*We need to either have User allow partially-trusted
callers, or we need to have Program be fully-trusted.
The former is the quicker to do, though the latter is
more likely to be what one would want for real*/
[assembly:AllowPartiallyTrustedCallers]
namespace AllowCallsOnNull
{
public class User
{
public bool IsAuthorized
{
get
{
//Perverse because someone writing in C# should be expected to be friendly to
//C#! This though doesn't apply to someone writing in another language who may
//not know C# has difficulties calling this.
//Still, don't do this:
if(this == null)
{
Console.Error.WriteLine("I don't exist!");
return false;
}
/*Real code to work out if the user is authorised
would go here. We're just going to return true
to demonstrate the point*/
Console.Error.WriteLine("I'm a real boy! I mean, user!");
return true;
}
}
}
class Program
{
public static void Main(string[] args)
{
//Set-up the helper that calls IsAuthorized on a
//User, that may be null.
DynamicMethod dynM = new DynamicMethod(string.Empty, typeof(bool), new Type[]{typeof(User)}, typeof(object));
ILGenerator ilGen = dynM.GetILGenerator(7);
ilGen.Emit(OpCodes.Ldarg_0);
ilGen.Emit(OpCodes.Call, typeof(User).GetProperty("IsAuthorized").GetGetMethod());
ilGen.Emit(OpCodes.Ret);
Func<User, bool> CheckAuthorized = (Func<User, bool>)dynM.CreateDelegate(typeof(Func<User, bool>));
//Now call it, first on null, then on an object
Console.WriteLine(CheckAuthorized(null)); //false
Console.WriteLine(CheckAuthorized(new User()));//true
//Wait for input so the user will actually see this.
Console.ReadKey(true);
}
}
}
Oh, and a real-life practical concern in this. The good thing about C#'s behaviour is that it causes fail-fast on calls on null-references that would fail anyway because they access a field or virtual somewhere in the middle. This means we don't have to worry about whether we're in a null instance when writing calls. If however you want to be bullet-proof in a fully public method (that is, a public method of a public class), then you can't depend on this. If it's vital that step 1 of a method is always followed by step 2, and step 2 would only fail if called on a null instance, then there should be a self-null check. This is rarely going to happen, but it could cause bugs for non-C# users that you'll never be able to reproduce in C# without using the above technique.
*Though, that is specific to their compiler - it's undefined per the C++ standard IIRC.
Can you use a struct instead? Then it should not ever be null.
You can't reference a property if you do not have a valid instance reference. If you want to be able to reference a property even with a null reference and not put the onus of null-checking on the caller, one way is a static method in User:
static bool IsAuthorized(User user)
{
if(user!=null)
{
return user.IsAuthorized;
}
else
{
return false;
}
}
Then, when you want to check your authorization, instead of:
if(thisUser.IsAuthorized)
Do:
if(User.IsAuthorized(thisUser))
The only way this can work is if you use an extension method or other static method to handle the null reference.
NullReferenceExceptions (NullPointerExceptions for the Javaheads; roughly synonymous) occur when code is told to call a method belonging to an object instance that doesn't actually exist. The thing you must keep in mind is that null is not actually any object. A variable of a type can be set to null, but that simply means the variable doesn't reference an instance.
Therein lies the problem; if a variable, regardless of its type (as long as that's a nullable type), is null, then there isn't an instance on which to call the method, and an instance is required for instance methods because that's how the program determines the state of members accessible to the method. If MyClass had a MyField and MyMethod(), and you called MyMethod on a null reference of MyClass, what's the value of MyField?
The solution is usually to move to static scope. Static members (and classes) are guaranteed to have state because they are instantiated once at runtime (usually just-in-time, as in before first reference). Because they always have state, they can always be called and so can be given things to do that may not be able to be done at the instance level. Here's a method you can use in C# to return a value from an object member chain which may otherwise result in an NRE:
public static TOut ValueOrDefault<TIn, TOut>(this TIn input, Func<TIn, TOut> projection,
TOut defaultValue = default(TOut))
{
try
{
var result = projection(input);
if (result == null) result = defaultValue;
return result;
}
catch (NullReferenceException) //most nulls result in one of these.
{
return defaultValue;
}
catch (InvalidOperationException) //Nullable<T>s with no value throw these
{
return defaultValue;
}
}
Usage:
class MyClass {public MyClass2 MyField;}
class MyClass2 {public List<string> MyItems; public int? MyNullableField;}
...
var myClass = null;
//returns 0; myClass is null
var result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass = new MyClass();
//returns 0; MyField is null
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass.MyField = new MyClass2();
//returns 0; MyItems is null
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
myClass.MyField.MyItems = new List<string>();
//returns 0, but now that's the actual result of the Count property;
//the entire chain is valid
result = myClass.ValueOrDefault(x=>x.MyField.MyItems.Count);
//returns null, because FirstOrDefault() returns null
var myString = myClass.ValueOrDefault(x=>x.MyField.MyItems.FirstOrDefault());
myClass.MyField.MyItems.Add("A string");
//returns "A string"
myString = myClass.ValueOrDefault(x=>x.MyField.MyItems.FirstOrDefault());
//returns 0, because MyNullableField is null; the exception caught here is not an NRE,
//but an InvalidOperationException
var myValue = myClass.ValueOrDefault(x=>x.MyField.MyNullableField.Value);
While this method has value in situations which would otherwise call for long nested ternary operators to produce something (anything) to show the user or use in a calculation, I do NOT recommend using this pattern to perform actions (void methods). Because no NREs or IOEs will be thrown out, you'll never know if what you asked it to do was actually done. You may be able to get away with a "TryPerformAction()" method which returns true or false, and/or has an output parameter containing the thrown exception (if any). But if you're going to go to that kind of trouble, why not just try/catch the thing yourself?

When are properties in closures evaluated?

Several methods in our code base use a 'MaybeObject' that can be passed into functions when a result might be known, or might rely on an external webservice call that has not yet been carried out. For example, the property below can either have a specified known value, or if not specified and called after the async call is complete it will return the result of the Async call.
private string _internalString;
public string stringProp
{
get
{
if (!string.IsNullOrEmpty(_internalString))
return _internalString;
return resultOfAsyncCallFromSomewhereElse;
}
set { _internalString = value; }
}
Obviously, trying to reference the property before the async call is complete would cause a null reference exception so we also have a flag to check if the value is available.
The question is, in the code below would the creation of the lambda try and evaluate stringProp (which might not be populated yet), or would evaluation be deferred until the resulting Action is called (which would be after checking the async operation is complete)?
public Action ExampleMethod(MaybeObject maybe)
{
return () => doSomethingWithString(maybe.stringProp);
}
In C# all would be evaluated whilst execution since C# lambda Closures is not a true Closure which able to resolve a state of captured environment in moment of creation.
() => doSomethingWithString(maybe.stringProp);
Here is even reference maybe could be null and you won't got any issues like NullReferenceException until executing a delegate. This trick sometimes used for late-bound value resolving.
Wikipedia: Closure:
A closure retains a reference to the environment at the time it
was created (for example, to the current value of a local variable
in the enclosing scope) while a generic anonymous function need not do
this.
Nice overview of C# Closure specifics - Anonymous methods and closures in C#
From the definition of Closure it can be inferred that Closure
remembers the values of the variables during its creation. However in
C# the outer local variable (i in this case) is shared with the
anonymous method by creating it on the heap. This means any change to
it in the anonymous method changes the original value and when the
method is called the second time it gets the modified value of i as 1
(see second line of output). This leads many to argue that anonymous
method is not actually a Closure as by its definition the value of a
variable at the time of creation of the Closure should be remembered
and not modifiable.
Evaluation will be deferred until the resulting Action is called.
The code referenced by a delegate is only executed when the delegate itself is explicitly invoked, regardless of how the delegate itself was created.
For example, these ways of passing the code to execute through the Action delegate are all equivalent, and the doSomethingWithString method won't be executed until a call to Action() is made:
Explicit method (.NET 1.1):
private MaybeObject maybe;
public Action ExampleMethod()
{
return new Action(DoSomethingWithMaybeObject);
}
private void DoSomethingWithMaybeObject()
{
doSomethingWithString(maybe.stringProp)
}
Anonymous method (.NET 2.0):
public Action ExampleMethod(MaybeObject maybe)
{
return delegate() { doSomethingWithString(maybe.stringProp) };
}
Lambda (.NET 3.5):
public Action ExampleMethod(MaybeObject maybe)
{
return () => doSomethingWithString(maybe.stringProp);
}
See also:
Delegates
Anonymous Methods
Lambda Expressions
Properties in closures are not evaluated until the action is run because properties are methods, not values. Accessing MyObject.MyProperty is like calling the code MyObject.get_MyProperty(), so you can get different behavior when using a property vs. using the underlying variable.
In .net closures are passed as reference so they are executed as they are evaluated, the same reason you can do something like this.
EventHandler handler = null;
handler = (sender, args) => { // event handler do something};
SomeEvent += handler;
it would be deffered.
ExampleMethod() returns a delegate to the anonymous function () => doSomethingWithString(maybe.stringProp), so doSomethingWithString() won't be called until that delegate is called
You should try this yourself to see what happens!
In this case it seems the closure is really around the MaybeObject, not just the string property (because the object is passed to the Action). The string property is not accessed until the Action is executed.
But even if the string itself were the variable given to the closure...
string s = "";
Func<bool> isGood = () => s == "Good";
s = "Good";
Console.WriteLine(isGood());
// prints 'True'
You can see here that the closure is made around a string, but it isn't evaluated until execution.
Delegates work just like any other function - they don't actually do anything until they are called.

null target of extension method

public static IFoo Bar<T>(this IFoo target, ...)
{
// I'm curious about how useful this check is.
if (target == null) throw new ArgumentNullException("target");
...
}
(1) The code above seems strange to me because I feel like in any case the calling code would be the one to check that. Is there some subtlety to extension methods in this area that applies?
(2) Is there a legitimate pattern that leverages the fact that the target can be null? I ask this as a consequence of wondering why calling an extension method on a null reference wouldn't generate the runtime exception the same way as if you called an instance method on a null reference.
Consider that null can be an argument to a method. Consider also that the extension method foo.Bar<int>(); is really just syntactic sugar for IFooExtensions.Bar<int>(foo); and you will see that, yes, the argument can indeed be null so if you're doing something with the argument, it may certainly be appropriate to test it for null (or simply let a NullReferenceException be thrown, take your pick).
Note: You would not get an exception merely by calling it with a null referenced object, because remember that the method does not actually belong to the object. You only get the exception if (a) you purposefully throw one yourself or (b) the method body actually causes it by trying to work with the instance that is null.
(2) Is there a legitimate pattern that
leverages the fact that the target can
be null? I ask this as a consequence
of wondering why calling an extension
method on a null reference wouldn't
generate the runtime exception the
same way as if you called an instance
method on a null reference.
Well, here's one use of it.
public static class UtilityExtensions
{
public static void ThrowIfNull( this object obj, string argName )
{
if ( obj == null )
{
throw new ArgumentNullException( argName );
}
}
}
Now you can write null checks easily and on one line (helpful if your coding convention forces you to use braces with all if statements).
public void Foo(string bar)
{
bar.ThrowIfNull("bar");
// ...
}
Whether or not you consider that a "legitimate" pattern is up to you, but I'd be very sad if the runtime was changed to make extension method invocations on null references throw exceptions.
Since extension methods really are only syntactic sugar for calling a static method with the object as the first parameter, I don't see why null for this parameter value shouldn't be allowed.

Throwing ArgumentNullException

Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example):
void someMethod(SomeClass x)
{
if (x == null){
throw new ArgumentNullException("someMethod received a null argument!");
}
x.doSomething();
}
Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()?
Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?
I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object.
If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception.
If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it.
I always follow the practice of fail fast. If your method is dependent on X and you understand X might be passed in null, null check it and raise the exception immediately instead of prolonging the point of failure.
2016 update:
Real world example. I strongly recommend the usage of JetBrains Annotations.
[Pure]
public static object Call([NotNull] Type declaringType,
[NotNull] string methodName,
[CanBeNull] object instance)
{
if (declaringType == null) throw new ArgumentNullException(nameof(declaringType));
if (methodName == null) throw new ArgumentNullException(nameof(methodName));
Guard statements have been vastly improved with C# 6 providing the nameof operator.
I prefer the explicit exception, for these reasons:
If the method has more than one SomeClass argument it gives you the opportunity to say which one it is (everything else is available in the call stack).
What if you do something that may have a side effect before referencing x?
No excuse not to make the check these days. C# has moved on and you can do this very neatly using a discard and a null coalescing operator:
_ = declaringType ?? throw new ArgumentNullException(nameof(declaringType));
_ = methodname ?? throw new ArgumentNullException(nameof(methodName));
I agree with the idea of failing fast - however it is wise to know why failing fast is practical. Consider this example:
void someMethod(SomeClass x)
{
x.Property.doSomething();
}
If you rely on the NullReferenceException to tell you that something was wrong, how will you know what was null? The stack trace will only give you a line number, not which reference was null. In this example x or x.Property could both have been null and without failing fast with aggressive checking beforehand, you will not know which it is.
I'd prefer the parameter check with the explicit ArgumentNullException, too.
Looking at the metadata:
//
// Summary:
// Initializes a new instance of the System.ArgumentNullException class with
// the name of the parameter that causes this exception.
//
// Parameters:
// paramName:
// The name of the parameter that caused the exception.
public ArgumentNullException(string paramName);
You can see, that the string should be the name of the parameter, that is null, and so give the developer a hint on what is going wrong.
I strongly agree with #tvanfosson. Adding to his answer, with .net 6 it’s very easy to throw the ArgumentNullException.
ArgumentNullException.ThrowIfNull(object);
Here’s the official documentation.
You should explicitly throw an ArgumentNullException if you are expecting the input to not be null. You might want to write a class called Guard that provides helper methods for this. So your code will be:
void someMethod(SomeClass x, SomeClass y)
{
Guard.NotNull(x,"x","someMethod received a null x argument!");
Guard.NotNull(y,"y","someMethod received a null y argument!");
x.doSomething();
y.doSomething();
}
The NonNull method would do the nullity check and throw a NullArgumentException with the error message specified in the call.
It is better to throw the ArgumentNullException sooner rather than later. If you throw it, you can provide more helpful information on the problem than a NullReferenceException.
Do it explicitly if you do not want a Null value. Otherwise, when someone else look at your code, they will think that passing a Null value is acceptable.
Do it as early as you can. This way, you do not propagate the "wrong" behavior of having a Null when it's not supposed to.
If you program defensively you should fail fast. So check your inputs and error out at the beginning of your code. You should be nice to your caller and give them the most descriptive error message you can.
I'll probably be downvoted for this, but I think completely different.
What about following a good practice called "never pass null" and remove the ugly exception checking?
If the parameter is an object, DO NOT PASS NULL. Also, DO NOT RETURN NULL. You can even use the Null object pattern to help with that.
If it's optional, use default values (if your language supports them) or create an overload.
Much cleaner than ugly exceptions.
Since .NET 6 you can throw the argument null exception in one line for instance:
int? foo = null;
ArgumentNullException.ThrowIfNull(foo);
This will check if foo is null and throw an error. You can pass a second parameter to set the parameter name, but this is not recommended.
https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-6.0
You can use syntax like the following to not just throw an ArgumentNullException but have that exception name the parameter as part of its error text as well. E.g.;
void SomeMethod(SomeObject someObject)
{
Throw.IfArgNull(() => someObject);
//... do more stuff
}
The class used to raise the exception is;
public static class Throw
{
public static void IfArgNull<T>(Expression<Func<T>> arg)
{
if (arg == null)
{
throw new ArgumentNullException(nameof(arg), "There is no expression with which to test the object's value.");
}
// get the variable name of the argument
MemberExpression metaData = arg.Body as MemberExpression;
if (metaData == null)
{
throw new ArgumentException("Unable to retrieve the name of the object being tested.", nameof(arg));
}
// can the data type be null at all
string argName = metaData.Member.Name;
Type type = typeof(T);
if (type.IsValueType && Nullable.GetUnderlyingType(type) == null)
{
throw new ArgumentException("The expression does not specify a nullible type.", argName);
}
// get the value and check for null
if (arg.Compile()() == null)
{
throw new ArgumentNullException(argName);
}
}
}
All code examples use error prone IF clause, where one use equal operator ==.
What happen, if type override == ?
On C# 7 and greater, use constant pattern matching.
example:
if (something is null)
{
throw new ArgumentNullException(nameof(something), "Can't be null.");
}

Categories