Home > Enterprise >  How to avoid nullability warning when using existing APIs
How to avoid nullability warning when using existing APIs

Time:12-19

I get the following compiler warning when implementing the frameworks IComparer interface. I understand the reason why, but in my case I ensure that I initialize all values of the collection with an instance. How can I avoid the warning? I tried the bang operator but it doesn't seem to be allowed here. Maybe there is an alternative for collections which are known to have no null elements?

warning CS8767: Nullability of reference types in type of parameter 'x' of 'int FooComparer .Compare(Foo x, Foo y)' doesn't match implicitly implemented member 'int IComparer.Compare(Foo? x, Foo? y)' (possibly because of nullability attributes).

class FooComparer : IComparer<Foo>
{
    public int Compare(Foo x, Foo y)
    {
        return y.Bar() - x.Bar();
    }
}

CodePudding user response:

Ok I got it solved. Need to declare the arguments as nullable as the contract needs, but in implementation have to use bang to tell what we expect:

class FooComparer : IComparer<Foo>
{
    public int Compare(Foo? x, Foo? y)
    {
        return y!.Bar() - x!.Bar();
    }
}

I wished that I could declare the non-nullability already in the API.

CodePudding user response:

you can disable the warning if you are sure about nullability.

#pragma warning disable CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).
    public int Compare(Foo x, Foo y)
#pragma warning restore CS8767 // Nullability of reference types in type of parameter doesn't match implicitly implemented member (possibly because of nullability attributes).

you can refer to this if you want to disable this on the project level.

  • Related