Null reference exception after checking for null (checking for null doesn't work)

null reference exception object not set to an instance of an object
how to fix object reference not set to an instance of an object
nullreferenceexception: object reference not set to an instance of an object asp net core
null reference exception unity
nullreferenceexception: object reference not set to an instance of an object unity
how to handle null reference exception in c#
object reference not set to an instance of an object, visual studio
object reference not set to an instance of an object c#

Take a look at this code:

var categories = tokens.SelectMany(x => x.Categories);

if (categories != null)
{
    if (categories.Contains("interp")) //null ref exception
    {
        return null;
    }
}

I get Null Reference Exception when I try fo find "interp" string within categories. So it seems that "categories != null" doesn't work.

I found some suggestions (here How to check if IEnumerable is null or empty?) but they involve using .Any(). But it only makes the exception accure earlier (while using .Any()). Even ?.Any() throws the exception.

Any ideas?

This code will throw an NRE in categories.Contains only if the Categories property is null.

The following code will throw :

class Token
{
    public string[] Categories{get;set;}
}

var tokens=new []{new Token()};
var categories = tokens.SelectMany(x => x.Categories);
if (categories != null)
{
    if (categories.Contains("interp")) 
    {
        Console.WriteLine("Found");
    }
}

But so would

tokens.SelectMany(x => x.Categories).ToArray();

The thing that actually throws is the nested iterator inside SelectMany, not ToArray() or Contains. The stack trace for that exception is :

at System.Linq.Enumerable.<SelectManyIterator>d__17`2.MoveNext()
at System.Linq.Enumerable.Contains[TSource](IEnumerable`1 source, TSource value, IEqualityComparer`1 comparer)
at UserQuery.Main()

SelectMany will try to iterate over each Categories entry, find that the property is actually null and throw.

The quick fix is to add a Where before SelectMany to eliminate null Categories :

var categories = tokens.Where(x=>x.Categories!=null).SelectMany(x => x.Categories);

The real solution is to ensure Categories is never empty - it should be initialized to an empty array, list, whatever upon construction. When reassigned, it should never be set to null.

This example sets the _categories field to new string[0] even if a caller passes null to Categories

class Token
{
    string[] _categories=new string[0];
    public string[] Categories{
        get => _categories;
        set => _categories = value??new string[0];
    }

}

With that, Where(x=>x.Categories !=null) is no longer necessary

NullReferenceException Class (System), The following example does this by calling a type's class constructor. Despite this check, however, the method throws a NullReferenceException exception It's usually better to avoid a NullReferenceException than to handle it after it occurs� If a reference variable isn’t referencing an object, then it’ll be treated as null. The run-time will tell you that you are trying to access an object, when the variable is null by issuing a NullReferenceException. Reference variables in c# and JavaScript are similar in concept to pointers in C and C++.

When working with collections and IEnumerable<T> avoid using null; if you have nothing to return, return an empty collection (not null).

In your particular case SelectMany will never return null, but empty collection, that's why categories != null check is useless, and you have to check tokens instead

if (null != tokens)
  // Where(x => x != null) - to be on the safe side if x == null or x.Categories == null
  if (tokens
       .Where(x => x != null && x.Categories != null)
       .SelectMany(x => x.Categories)
       .Contains("interp"))
    return null;

However, constant checking for null makes code being unreadable, that's why try check for null once:

// if tokens is null change it for an empty collection
tokens = tokens ?? new MyToken[0];

...

if (tokens 
      .Where(x => x != null && x.Categories != null)
      .SelectMany(x => x.Categories)
      .Contains("interp"))
    return null;

Object Reference Not Set to an Instance of an Object: How To Solve It, How can you stop the NullReferenceException from happening in your code? After this round of theoretical definitions, we'll get to more practical and that's what we call a null reference: a reference that doesn't point to any object. Instead of having a crazy amount of “variable != null” type checks, you� A null check is one of the most common operations in .NET development. ReSharper is one tool that takes null checks seriously by providing special support to developers working with entities that can potentially be null. The first thing ReSharper does is detect the possibility of a NullReferenceException occurring. For example, say we try to

var categories = tokens.SelectMany(x => x.Categories).ToList();

add .ToList() and you should know more about where the error is with that information we have in the post, we can only guess

Debugging System.NullReferenceException, NullReferenceException - Object reference not set to an instance of an object If null is an allowed value of an object, you will need to check for it. warning CS8625: Cannot convert null literal to non-nullable reference type. NullReferenceException or ‘Object Reference not set to an Instance of an Object’ is a very common exception. That indicates, you are trying to access member fields, or function types, on an object reference that points to null. This means the reference is null, and you cannot access members through a null reference. Example:

Can use where clause and make it as list , then just check if there is any element in the list

 var categories = list.Where(x => x.Categories.Contains("interp")).ToList();
 if (categories.Count() == 0)
  {
     return null;

   }

C# NullReferenceException and Null Parameter, Review the NullReferenceException, which is thrown when trying to access a field Note: This means that the string variable does not point to any object on the managed heap. The Test method checks its parameter against the null literal. Use tools like Resharper to help point out potential null reference exceptions; Avoiding NullReferenceException With C# 8.0’s Nullable Types. One of the main causes of bugs with null reference is the fact that in C every reference type object can be null, all the time.

What is a Null Reference Exception? - Unity, If a reference variable isn't referencing an object, then it'll be treated as null . a game object that doesn't exist the run-time gives us a NullReferenceException NullReferenceException can be avoided by writing code that checks for null� In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when program attempts to use an object reference that has the null value. These can be: Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array.

NullReferenceException when checking for null, NullReferenceException when checking for null. I already checked for this one and I understand at this point that this is probably the intended� Null pointer/reference errors, more often than not, are programmer errors. Programmer errors are often best dealt with by failing immediately and loudly. You have three general ways to deal with the problem in this situation: Don't bother checking, and just let the runtime throw the nullpointer exception.

How to C# String Null, A null string does not refer to an instance of a System.String object and any attempt to call a method on a null string results in a NullReferenceException. You may use the null keyword to check or assign the value of an object. string str =null� A null object is one that doesn't have any referenced value. The null object pattern is a behavioral design pattern that is used to provide a consistent return object in lieu of null.

Comments
  • Check tokens != null if tokens is not null, SelectMany will never return null but empty enumerable
  • Maybe an element of tokens is null. x.Categories would then throw an exception when you call Contains.
  • Null checks work. If you get an NRE it means something else failed. Post the full exception text, including the call stack. Perhaps it was a different line that threw, or Enumerable.Contains threw because categories is empty. Or perhaps x.Categories actually contained null entries that ended up in the categories variable.
  • What type is your selectmany returning?
  • It would be awesome if you could provide a minimal reproducible example. What is the type of categories?
  • This is the only answer that seems to have got it right. tokens can never be null if SelectMany doesn't throw an exception. Upvote!
  • ToList(); - try avoiding materialization when you don't have to do it; imaging that tokens.SelectMany usually returns millions of items (what a huge list we create for nothing since Contains doesn't want it)