Skip to content

Missing nullable warning in generic methods #35602

@jairbubbles

Description

@jairbubbles

Version Used:

Microsoft.Net.Tool@3.1.0-beta3-final

Steps to Reproduce:

  1. Unzip TestNullable.zip
  2. Build

Expected Behavior:

  • Have a possible null reference warning with all method calls using possibleNullValue.
  • Have a warning on all methods that returns possibleNullValue asking to return a nullable.

Actual Behavior:

I only have a "possible null reference" warning on the last Check(value) (in the generic method). In fact I don't think the compiler really knows possibleNullValue can really be null so it looks like a bug to me (even if the warning is totally valid).

Adding the code error here so that people don't have to open the .zip:

class Program
{
    static void Main(string[] args)
    {
        Get();
        GetGeneric<string>();
    }

    static void Check(object value) { }

    static string Get()
    {
        var possibleNullValue = JsonConvert.DeserializeObject<string>("null");

        if (possibleNullValue == null)
        {
            Console.WriteLine("null value");
        }

        Check(possibleNullValue);

        return possibleNullValue;
    }

    static T GetGeneric<T>()
    {
        var possibleNullValue = JsonConvert.DeserializeObject<T>("null");

        if (possibleNullValue == null)
        {
            Console.WriteLine("null value");
        }

        Check(possibleNullValue); // "Possible null reference" warning here

        return possibleNullValue;
    }
}

[jcouv updated:]
I think we've narrowed down to the most questionable/suspicious scenario:

public static class JsonConvert
{
    public static T DeserializeObject<T>() => default;
}

#nullable safeonly

class NullTestWithoutContraint
{
    static T GetGeneric<T>()
    {
        var possibleNullValue = JsonConvert.DeserializeObject<T>();

       if (possibleNullValue is null) {} 
  
       return possibleNullValue;  // expecting a warning here, if T=string for example
    }
}

(see on sharplab)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status

    Active/Investigating

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions