Check out the following code:
private void Foo(object bar)
{
Type type = bar.GetType();
if (type != null) // Expression is always true
{
}
}
ReSharper claims type will never be null. That's obvious to me because there's always going to be a type for bar, but how does ReSharper know that? How can it know that the result of a method will never be null?
Type is not a struct so it can't be that. And if the method were written by me, then the return value could certainly be null (not necessarily GetType, but something else).
Is ReSharper clever enough to know that, for only that particular method, the result will never be null? (Like there's a hard-coded list of known .NET methods which will never return null.)
JetBrains perfectly explains how ReSharper does this in their features list.
Summary from link (this particular question is about NotNullAttribute):
We have analyzed a great share of .NET Framework Class Library, as well as NUnit Framework, and annotated it through external XML files, using a set of custom attributes from the JetBrains.Annotations namespace, specifically:
StringFormatMethodAttribute (for methods that take format strings as parameters)
InvokerParameterNameAttribute (for methods with string literal arguments that should match one of caller parameters)
AssertionMethodAttribute (for assertion methods)
AssertionConditionAttribute (for condition parameters of assertion methods)
TerminatesProgramAttribute (for methods that terminate control flow)
CanBeNullAttribute (for values that can be null)
NotNullAttribute (for values that can not be null)
UsedImplicitlyAttribute (for entities that should not be marked as unused)
MeansImplicitUseAttribute (for extending semantics of any other attribute to mean that the corresponding entity should not be marked as unused)
Yes, it basically has knowledge of some well-known methods. You should find the same for string concatenation too, for example:
string x = null;
string y = null;
string z = x + y;
if (z == null)
{
// ReSharper should warn about this never executing
}
Now the same information is also becoming available via Code Contracts - I don't know whether JetBrains is hooking directly into this information, has its own database, or a mixture of the two.
GetType is not virtual. Your assumption is most likely correct in your last statement.
Edit: to answer your comment question - it can't infer with your methods out of the box.
object.GetType is not virtual, so you cannot yourself implement a version that returns a null value. Therefore, if bar is null, you will get a NullReferenceException and otherwise, type will never by null.
Related
Can this overload of XPathNavigator.Evaluate return null ?
// Can "result" be null ?
object result = xmlDoc.CreateNavigator().Evaluate(xpathString);
If the answer is No, then why Resharper says that result maybe null ?
string str = result.ToString(); // Resharper: Possible NullReferenceException
I found nothing in the documentation about an input that might cause it to return null. I also tried inspecting the Reference Source for this function, but it was unfruitful.
I know that R# uses code annotations, but I still don't trust this warning as I tried different inputs with none of them returns null.
Looking at the code, it does look like it would be highly unlikely to get a null from XPathNavigator.Evaluate. There are a couple of possible code paths that might get you a null, but I suspect they're pathological edge cases (if evaluating a function that should be a number function, but isn't, or if the operand to a query is already null). I doubt these would happen under normal circumstances.
I don't know why ReSharper has the [CanBeNull] annotation on the return value. If I had to guess, I'd say it's because the method is virtual, and therefore there's no way to guarantee that the implementation will always return a value. Or because it calls an abstract method on another class that doesn't have any null-ness guarantees, and there's no check on the return of that value, so again, there's no guarantee that it won't be null.
The annotations are based on static control flow analysis, and that can only get you so far. ReSharper will provide the strongest hints that it can. If it knows it's not null, it will annotate it so, if it doesn't know, it will flag it [CanBeNull], and err on the side of caution.
For example, you usually don't want parameters in a constructor to be null, so it's very normal to see some thing like
if (someArg == null)
{
throw new ArgumentNullException(nameof(someArg));
}
if (otherArg == null)
{
throw new ArgumentNullException(nameof(otherArg));
}
It does clutter the code a bit.
Is there any way to check an argument of a list of arguments better than this?
Something like "check all of the arguments and throw an ArgumentNullException if any of them is null and that provides you with the arguments that were null.
By the way, regarding duplicate question claims, this is not about marking arguments with attributes or something that is built-in, but what some call it Guard Clauses to guarantee that an object receives initialized dependencies.
With newer version of C# language you can write this without additional library or additional method call:
_ = someArg ?? throw new ArgumentNullException(nameof(someArg));
_ = otherArg ?? throw new ArgumentNullException(nameof(otherArg));
Starting from .NET6 you can also write this:
ArgumentNullException.ThrowIfNull(someArg);
Starting from .NET7 you can handle empty string and null checking:
ArgumentException.ThrowIfNullOrEmpty(someStringArg);
public static class Ensure
{
/// <summary>
/// Ensures that the specified argument is not null.
/// </summary>
/// <param name="argumentName">Name of the argument.</param>
/// <param name="argument">The argument.</param>
[DebuggerStepThrough]
[ContractAnnotation("halt <= argument:null")]
public static void ArgumentNotNull(object argument, [InvokerParameterName] string argumentName)
{
if (argument == null)
{
throw new ArgumentNullException(argumentName);
}
}
}
usage:
// C# < 6
public Constructor([NotNull] object foo)
{
Ensure.ArgumentNotNull(foo, "foo");
...
}
// C# >= 6
public Constructor([NotNull] object bar)
{
Ensure.ArgumentNotNull(bar, nameof(bar));
...
}
The DebuggerStepThroughAttribute comes in quite handy so that in case of an exception while debugging (or when I attach the debugger after the exception occurred) I will not end up inside the ArgumentNotNull method but instead at the calling method where the null reference actually happened.
I am using ReSharper Contract Annotations.
The ContractAnnotationAttribute makes sure that I never misspell
the argument ("foo") and also renames it automatically if I rename
the foo symbol.
The NotNullAttribute helps ReSharper with code analysis. So if I do new Constructor(null) I will get a warning from ReSharper that this will lead to an exception.
If you do not like to annotate your code directly,
you can also do the same thing with external XML-files that you could deploy with your library and that users can optionally reference in their ReSharper.
If you have too many parameters in your constructors, you'd better revise them, but that's another story.
To decrease boilerplate validation code many guys write Guard utility classes like this:
public static class Guard
{
public static void ThrowIfNull(object argumentValue, string argumentName)
{
if (argumentValue == null)
{
throw new ArgumentNullException(argumentName);
}
}
// other validation methods
}
(You can add other validation methods that might be necessary to that Guard class).
Thus it only takes one line of code to validate a parameter:
private static void Foo(object obj)
{
Guard.ThrowIfNull(obj, "obj");
}
Null references are one sort of troubles you have to guard against. But, they are not the only one. The problem is wider than that, and it boils down to this: Method accepts instances of a certain type, but it cannot handle all instances.
In other words, domain of the method is larger than the set of values it handles. Guard clauses are then used to assert that actual parameter does not fall into that "gray zone" of the method's domain which cannot be handled.
Now, we have null references, as a value which is typically outside the acceptable set of values. On the other hand, it often happens that some non-null elements of the set are also unacceptable (e.g. empty string).
In that case, it may turn out that the method signature is too broad, which then indicates a design problem. That may lead to a redesign, e.g. defining a subtype, typically a derived interface, which restricts domain of the method and makes some of the guard clauses disappear. You can find an example in this article: Why do We Need Guard Clauses?
With newer version of C# (C# 10, .NET6 will be released in a few days) you can even do:
ArgumentNullException.ThrowIfNull(someArg);
Doc: https://learn.microsoft.com/en-us/dotnet/api/system.argumentnullexception.throwifnull?view=net-6.0
Ardalis has an excellent GuardClauses library.
It's nice to use Guard.Against.Null(message, nameof(message));
In C# 8.0 and later, new helps are available. C# 8.0 introduces non-nullable reference types (a feature somewhat confusingly called "nullable reference types" in the docs). Prior to C# 8.0, all reference types could be set to null. But now with C# 8.0 and the 'nullable' project setting, we can say that reference types are by default non-nullable, and then make our variables and parameters nullable on a case-by-case basis.
So whereas at the moment, we recognize code like this:
public void MyFunction(int thisCannotBeNull, int? thisCouldBeNull)
{
// no need for checking my thisCannotBeNull parameter for null here
}
If you set <Nullable>enable</Nullable> for your C# v8.0+ project, you can do things like this too:
public void MyFunction(MyClass thisCannotBeNull, MyClass? thisCouldBeNull)
{
// static code analysis at compile time checks to see if thisCannotBeNull could be null
}
The null-checking is done at compile-time, using static code analysis. So if you've coded it in a way that means a null could turn up there, you'll get a compiler warning (which you can upgrade to an error if you want). So lots (but not all) of the situations where you need a run-time check for null parameters can be handled as a compile-time check based on your code.
The !! operator (not actually part of C#, but interesting story)
Microsoft attempted to introduce a new language feature that was known as parameter null checking or also as the bang bang operator in C# 10 and later again in C# 11, but decided to not release it.
It would have been the shortest way to do this (by far): only 2 exclamation marks !! right after the argument(s) you want to check for null.
Before:
public void test(string someArg){
if (someArg == null)
{
throw new ArgumentNullException(nameof(someArg));
}
// other code
}
With that new operator:
public void test(string someArg!!){
// other code
}
Calling test(null) would have lead to an ArgumentNullException telling you that someArg is null.
Microsoft mentioned it in early 2021, but it did not become part of C# 10: A video on the 'Microsoft Developer' YouTube channel explaining the new feature.
The feature was implemented in February 2022 for C#11, see on GitHub.
It was removed later see on Microsoft dev blog because of lots of criticism with the argument, that the bang bang operator is very shouty.
The developers of the C# language think, that there is a majority for such a feature, but that it's not as large as usual and that it's possible, that this features comes with a later C# version.
You might try my Heleonix.Guard library, which provides guard functionality.
You can write guard clauses like below:
// C# 7.2+: Non-Trailing named arguments
Throw.ArgumentNullException(when: param.IsNull(), nameof(param));
// OR
// Prior to C# 7.2: You can use a helper method 'When'
Throw.ArgumentNullException(When(param.IsNull()), nameof(param));
// OR
Throw.ArgumentNullException(param == null, nameof(param));
// OR
Throw.ArgumentNullException(When (param == null), nameof(param));
It provides throwing of many existing exceptions, and you can write custom extension methods for custom exceptions. Also, the library refers to the 'Heleonix.Extensions' library with predicative extensions like IsNull, IsNullOrEmptyOrWhitespace, IsLessThan and many more to check your arguments or variables against desired values. Unlike some other guard libraries with fluent interfaces, these extensions do not generate intermediate objects, and since implementation is really straightforward, they are performant.
If you want to save typing the argument name twice, like
Guard.AgainstNull(arg, nameof(arg));
check out YAGuard, where you can write
Guard.AgainstNull(arg);
No need to specify the name of the argument in the guard clause, but in the argument thrown, the name is correctly resolved.
It also supports guard-and-set in the form
MyProperty = Assign.IfNotNull(arg);
Nuget: YAGuard
Disclaimer: I'm the author of YAGuard.
The simplest approach I've found is inspired by Dapper's use of anonymous types.
I've written a Guard class that uses anonymous types to get name of properties.
The guard itself is the following
public class Guard
{
public static void ThrowIfNull(object param)
{
var props = param.GetType().GetProperties();
foreach (var prop in props)
{
var name = prop.Name;
var val = prop.GetValue(param, null);
_ = val ?? throw new ArgumentNullException(name);
}
}
}
You then use it like so
...
public void Method(string someValue, string otherValue)
{
Guard.ThrowIfNull(new { someValue, otherValue });
}
...
When the ArgumentNullException is thrown, reflection is used to determine the name of the property which will then be displayed in your exception
There is a nuget package called SwissKnife. Install SwissKnife from nuget gallery. It provides you with many options starting with null checking for arguments
Argument.IsNotNullOrEmpty(args,"args") under SwissKnife.Diagnostics.Contracts namespace alongwith with option idoim and many more. You can set Option<Class_Name> _someVar and then check if _someVar.IsSome or _someVar.IsNone. This helps against nullable classes as well. Hope this helps.
I've always thought that it's impossible for this to be null inside instance method body. Following simple program demonstrates that it is possible. Is this some documented behaviour?
class Foo
{
public void Bar()
{
Debug.Assert(this == null);
}
}
public static void Test()
{
var action = (Action)Delegate.CreateDelegate(typeof (Action), null, typeof(Foo).GetMethod("Bar"));
action();
}
UPDATE
I agree with the answers saying that it's how this method is documented. However, I don't really understand this behaviour. Especially because it's not how C# is designed.
We had gotten a report from somebody (likely one of the .NET groups
using C# (thought it wasn't yet named C# at that time)) who had
written code that called a method on a null pointer, but they didn’t
get an exception because the method didn’t access any fields (ie
“this” was null, but nothing in the method used it). That method then
called another method which did use the this point and threw an
exception, and a bit of head-scratching ensued. After they figured it
out, they sent us a note about it.
We thought that being able to call a method on a null instance was a
bit weird. Peter Golde did some testing to see what the perf impact
was of always using callvirt, and it was small enough that we decided
to make the change.
http://blogs.msdn.com/b/ericgu/archive/2008/07/02/why-does-c-always-use-callvirt.aspx
Because you're passing null into the firstArgument of Delegate.CreateDelegate
So you're calling an instance method on a null object.
http://msdn.microsoft.com/en-us/library/74x8f551.aspx
If firstArgument is a null reference and method is an instance method,
the result depends on the signatures of the delegate type type and of
method:
If the signature of type explicitly includes the hidden first
parameter of method, the delegate is said to represent an open
instance method. When the delegate is invoked, the first argument in
the argument list is passed to the hidden instance parameter of
method.
If the signatures of method and type match (that is, all parameter
types are compatible), then the delegate is said to be closed over a
null reference. Invoking the delegate is like calling an instance
method on a null instance, which is not a particularly useful thing to
do.
Sure you can call into a method if you are using the call IL instruction or the delegate approach. You will set this booby trap only off if you try to access member fields which will give you the NullReferenceException you did seek for.
try
int x;
public void Bar()
{
x = 1; // NullRefException
Debug.Assert(this == null);
}
The BCL does even contain explicit this == null checks to aid debugging for languages which do not use callvirt (like C#) all the time. See this question for further infos.
The String class for example has such checks. There is nothing mysterious about them except that you will not see the need for them in languages like C#.
// Determines whether two strings match.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(Object obj)
{
//this is necessary to guard against reverse-pinvokes and
//other callers who do not use the callvirt instruction
if (this == null)
throw new NullReferenceException();
String str = obj as String;
if (str == null)
return false;
if (Object.ReferenceEquals(this, obj))
return true;
return EqualsHelper(this, str);
}
Try the documentation for Delegate.CreateDelegate() at msdn.
You're "manually" calling everything, and thus instead of passing an instance in for the this pointer, you're passing null. So it can happen, but you have to try really really hard.
this is a reference, so there is no problem with its being null from the perspective of the type system.
You may ask why NullReferenceException was not thrown. The full list of circumstances when CLR throws that exception is documented. Your case is not listed. Yes, it is a callvirt, but to Delegate.Invoke (see here) rather than to Bar, and so the this reference is actually your non-null delegate!
The behavior you see has an interesting implementational consequence for CLR. A delegate has a Target property (corresponds to your this reference) that is quite frequently null, namely when the delegate is static (imagine Bar be static). Now there is, naturally, a private backing field for the property, called _target. Does _target contain a null for a static delegate? No it doesn't. It contains a reference to the delegate itself. Why not null? Because a null is a legitimate target of a delegate as your example shows and CLR does not have two flavors of a null pointer to distinguish the static delegate somehow.
This bit of trivium demonstrates that with delegates, null targets of instance methods are no afterthought. You may still be asking the ultimate question: but why they had to be supported?
The early CLR had an ambitious plan of becoming, among others, the platform of choice even for sworn C++ developers, a goal that was approached first with Managed C++ and then with C++/CLI. Some too challenging language features were omitten, but there was nothing really challenging about supporting instance methods executing without an instance, which is perfectly normal in C++. Including delegate support.
The ultimate answer therefore is: because C# and CLR are two different worlds.
More good reading and even better reading to show the design allowing null instances shows its traces even in very natural C# syntactic contexts.
this is a readonly reference in C# classes. Accordingly and as expected this can be used like any other references (in read only mode) ...
this == null // readonly - possible
this = new this() // write - not possible
For example, if I have a method defined as...
T Create()
{
T t = Factory.Create<T>();
// ...
Assert.IsNotNull(t, "Some message.");
// -or-
if (t == null) throw new Exception("...");
// -or- anything that verifies that it is not null
}
...and I am calling that method from somewhere else...
void SomewhereElse()
{
T t = Create();
// >><<
}
...at >><<, I know (meaning me, the person who wrote this) that t is guaranteed to not be null. Is there a way (an attribute, perhaps, that I have not found) to mark a method as ensuring that a reference type that it returns or otherwise passes out (perhaps an out parameter) is guaranteed by internal logic to not be null?
I have to sheepishly admit that ReSharper is mostly why I care as it highlights anything it thinks could cause either InvalidOperationException or NullReferenceException. I figure either it's reading something that I can mark on my methods or it just knows that Assert.IsNotNull, simple boolean checks or a few other things will remove the chance of something being null and that it can remove the highlight.
Any thoughts? Am I just falling victim to oh-my-god-resharper-highlights-it-I-have-to-fix-it disease?
If ReSharper is why you care then you can mark the Factory.Create<T>() method with their [NotNull] attribute described in their web help
Not sure how R# handles this, but the Contract.Assert method may be what you're looking for
You could put a constraint on T to only allow struct.
You could use a language extension that allows you to make stronger definitions of pre/post conditions for your function (contract based programming), like SpecSharp, or Code Contracts. Code Contracts seems to leverage built-in systems from C# 4.0. I have no experience with either - only heard of them.
Could you cast T to an object then check if its null?
var o = (object)Factory.Create<T>();
if(o == null) throw new Exception();
Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal null isn't being used anywhere for it and at run-time throw ArgumentNullException.
Currently I write something like ...
if (null == arg)
throw new ArgumentNullException("arg");
... for every argument that I expect to not be null.
On the same note, is there an opposite to Nullable<> whereby the following would fail:
NonNullable<string> s = null; // throw some kind of exception
There's nothing available at compile-time, unfortunately.
I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the Code Contracts stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "if (null == arg)" instead of "if (arg == null)"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.
I know I'm incredibly late to this question, but I feel the answer will become relevant as the latest major iteration of C# comes closer to release, then released. In C# 8.0 a major change will occur, C# will assume all types are considered not null.
According to Mads Torgersen:
The problem is that null references are so useful. In C#, they are the
default value of every reference type. What else would the default
value be? What other value would a variable have, until you can decide
what else to assign to it? What other value could we pave a freshly
allocated array of references over with, until you get around to
filling it in?
Also, sometimes null is a sensible value in and of itself. Sometimes
you want to represent the fact that, say, a field doesn’t have a
value. That it’s ok to pass “nothing” for a parameter. The emphasis is
on sometimes, though. And herein lies another part of the problem:
Languages like C# don’t let you express whether a null right here is a
good idea or not.
So the resolution outlined by Mads, is:
We believe that it is more common to want a reference not to be null. Nullable reference types
would be the rarer kind (though we don’t have good data to tell us by
how much), so they are the ones that should require a new annotation.
The language already has a notion of – and a syntax for – nullable value types. The analogy between the two would make the language
addition conceptually easier, and linguistically simpler.
It seems right that you shouldn’t burden yourself or your consumer with cumbersome null values unless you’ve actively decided that you
want them. Nulls, not the absence of them, should be the thing that
you explicitly have to opt in to.
An example of the desired feature:
public class Person
{
public string Name { get; set; } // Not Null
public string? Address { get; set; } // May be Null
}
The preview is available for Visual Studio 2017, 15.5.4+ preview.
I know this is a VERY old question, but this one was missing here:
If you use ReSharper/Rider you may use the Annotated Framework.
Edit: I just got a random -1 for this answer. That's fine. Just be aware it is still valid, even though it's not the recommended approach for C#8.0+ projects anymore (to understand why, see Greg's answer).
Check out the validators in the enterprise library. You can do something like :
private MyType _someVariable = TenantType.None;
[NotNullValidator(MessageTemplate = "Some Variable can not be empty")]
public MyType SomeVariable {
get {
return _someVariable;
}
set {
_someVariable = value;
}
}
Then in your code when you want to validate it:
Microsoft.Practices.EnterpriseLibrary.Validation.Validator myValidator = ValidationFactory.CreateValidator<MyClass>();
ValidationResults vrInfo = InternalValidator.Validate(myObject);
not the prettiest but:
public static bool ContainsNullParameters(object[] methodParams)
{
return (from o in methodParams where o == null).Count() > 0;
}
you could get more creative in the ContainsNullParameters method too:
public static bool ContainsNullParameters(Dictionary<string, object> methodParams, out ArgumentNullException containsNullParameters)
{
var nullParams = from o in methodParams
where o.Value == null
select o;
bool paramsNull = nullParams.Count() > 0;
if (paramsNull)
{
StringBuilder sb = new StringBuilder();
foreach (var param in nullParams)
sb.Append(param.Key + " is null. ");
containsNullParameters = new ArgumentNullException(sb.ToString());
}
else
containsNullParameters = null;
return paramsNull;
}
of course you could use an interceptor or reflection but these are easy to follow/use with little overhead
Ok this reply is a bit late, but here is how I am solving it:
public static string Default(this string x)
{
return x ?? "";
}
Use this exension method then you can treat null and empty string as the same thing.
E.g.
if (model.Day.Default() == "")
{
//.. Do something to handle no Day ..
}
Not ideal I know as you have to remember to call default everywhere but it is one solution.