Creating a new List<int>() throws a NullReferenceException.

Mark Curtis 0 Reputation points
2026-08-18T15:37:47.1+00:00

The following code throw a NullReferenceException on the hightlighted line:

using IS0AUTTSTContext db = GetDbContext();
List<TestRun> list = db.TestRuns.Where(t => t.ID > 0 && t.Definition!.Application!.Deleted == false).ToList();
 
 if (user != null && user.IsInRole("Basic"))
 {
     List<int> apps = [];    //<<<------- NRE Here!
     List<ApplicationUser> appUsers = db.ApplicationUsers.Where(au => au.UserID == user.DBUser!.ID).ToList();
     apps.AddRange(appUsers.Where(au => au != null).Select(au => au.AppID)?.ToList() ?? []);
}

but the following code does not:

using IS0AUTTSTContext db = GetDbContext();
List<TestRun> list = db.TestRuns.Where(t => t.ID > 0 && t.Definition!.Application!.Deleted == false).ToList();
List<int> apps = []; 
 
 if (user != null && user.IsInRole("Basic"))
 {
     List<ApplicationUser> appUsers = db.ApplicationUsers.Where(au => au.UserID == user.DBUser!.ID).ToList();
     apps.AddRange(appUsers.Where(au => au != null).Select(au => au.AppID)?.ToList() ?? []);
}

Can someone tell me why? This is in an ASP.NET Core Web API method.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Most helpful
  1. Tony Thach (WICLOUD CORPORATION) 445 Reputation points Microsoft External Staff Moderator
    2026-08-19T02:10:58.69+00:00

    Hi @Mark Curtis ,

    I created a minimal project to investigate the behavior described in your question.

    With the code exactly as posted, I could not reproduce a NullReferenceException from this statement when List<int> resolves to the standard .NET collection type:

    List<int> apps = [];
    

    For System.Collections.Generic.List<int>, [] is a C# collection expression that creates an empty list. The statement does not directly dereference a nullable object, so it is not sufficient by itself to throw a NullReferenceException. (Collection expressions)

    However, I was able to reproduce the same observable behavior only after deliberately adding behavior that is not present in the posted snippet and include detail files below:

    Program.cs.txt , HiddenList.cs.txt Debug console In that constructed reproduction:

    1. When the declaration was inside the if block, the debugger highlighted:
         List<int> apps = [];
      
    2. When the declaration was moved before the if statement, the exception disappeared.
    3. The actual null dereference was located in another source file.
    4. Source-line mapping associated the failing instruction with the list declaration, causing both the debugger and stack trace to report the declaration as the failure location.

    This is possible because debug symbols map compiled instructions to source locations. The highlighted source line is therefore a mapped location or call site and is not always the source statement that contains the underlying null dereference. (Line directives)

    Moving the declaration changed the result in my reproduction because it changed the execution order:

    Declaration inside the if:

    • user.IsInRole("Basic") is called
    • Some runtime state changes
    • List<int> is constructed
    • Hidden code dereferences null
    • The exception is reported at the mapped list declaration

    Declaration before the if:

    • List<int> is constructed first
    • The runtime state has not changed yet
    • user.IsInRole("Basic") is called afterward
    • The application continues

    This does not mean that your application has a custom List<T>, source-line directives, or the same hidden state. The reproduction only demonstrates that the reported symptom requires additional behavior, type resolution, generated code, state, or debug mapping that is not visible in the posted snippet.

    The following expressions in the posted code are more likely null-reference candidates:

    user.IsInRole("Basic")
    
    user.DBUser!.ID
    
    t.Definition!.Application!.Deleted
    

    The null-forgiving operator (!) only suppresses nullable warnings from the compiler. It has no runtime null-checking effect. For example, if user.DBUser is null, this still throws:

    user.DBUser!.ID
    

    (null-forgiving)

    As a quick type-resolution test, please temporarily replace:

    List<int> apps = [];
    

    with:

    System.Collections.Generic.List<int> apps = new();
    

    If this changes the behavior, List<T> may be resolving to a different type than expected through a namespace, alias, global using, or another declaration.

    If the behavior does not change, please perform a clean rebuild from the project directory:

    dotnet clean
    rmdir /s /q bin
    rmdir /s /q obj
    dotnet restore
    dotnet build
    

    Then reproduce the exception without Hot Reload or Edit and Continue.

    Please provide the following so that the actual null reference can be identified:

    1. The complete exception stack trace, including all inner exceptions.
    2. The complete ASP.NET Core Web API method without removing surrounding code.
    3. The .csproj file.
    4. Any aliases or declarations involving List.
    5. The relevant User declaration, particularly:
         IsInRole(...)
         DBUser
      
    6. The relevant declarations for:
         IS0AUTTSTContext
         ApplicationUser
         TestRun
         Definition
         Application
      

    The complete stack trace is particularly important. For example, if it contains:

    at SomeType.SomeMethod(...)
    at YourController.YourAction(...)
    

    then SomeType.SomeMethod(...) may contain the actual null dereference, even if the debugger highlights the list declaration in the controller.

    Based only on the posted snippet, creating an empty System.Collections.Generic.List<int> is not sufficient to cause a NullReferenceException. The behavior may be real, but additional project context is required to distinguish the highlighted source location from the actual null dereference and its root cause.

    If this explanation and the diagnostic steps were helpful, I would appreciate it if you could follow the instructions here, so that others experiencing similar behavior can benefit from the answer as well.  

    Was this answer helpful?

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 84,866 Reputation points
    2026-08-19T00:32:04.1033333+00:00

    Your code looks suspect. Why declare apps in an if statement scope, and not use it as a reference. Your code would run the same if you removed the if block..

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.