Skip to content

False positive of CA1508 related to nullability analysis (boxing, array allocation not recognized as potentially failing) #7795

@GeeLaw

Description

@GeeLaw

Consider the following csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <Platforms>AnyCPU</Platforms>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>disable</ImplicitUsings>
    <Nullable>disable</Nullable>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
    <EnableNETAnalyzers>true</EnableNETAnalyzers>
    <AnalysisLevel>latest-all</AnalysisLevel>
    <WarningLevel>9999</WarningLevel>
  </PropertyGroup>

</Project>

Write the following code:

using System;

static class Program
{
  public static object Foo()
  {
    object o = null;
    try
    {
      o = default(int);
      // o = new object[] { new object[1], new DateTime() };
      // o = 1.0f;
      // decimal d = 1.0m; o = d;
    }
    finally
    {
      if (o is not null) // CA1508: It thinks o is never null.
        Console.WriteLine();
    }
    return o;
  }
}

The CA1508 is incorrectly reported, because allocation could fail due to insufficient memory. Also, the array creation could fail due to being too long (e.g., int.MaxValue).

It appears this issue only arises for boxing (from existing value or default, including the default parameterless constructor) and array creation (including multi-dimensional arrays) if the array creation has no initializer or its initializer only recursively contains boxing and such array creations.


Version information

  • Windows 11 version 24H2 x64.
  • Visual Studio 18.2.1.
  • C# Tools 5.0.0-2.26054.2+ec501e4c6f2689c9c71e38ce72d892675965c392.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions