简体   繁体   中英

Can an indexer parameter ever be null?

This is a code from a class of mine with a custom indexer :

public string this[string key]
{
    get => /* ... */;
    set
    {
        if (key != null) doSomething(key, value);
    }
}

Now ReSharper underlines the key != null check and says:

Expression is always true.

While I do believe ReSharper is correct here, I cannot understand why.

Maybe the language spec enforces this?

My question:

Can an indexer parameter ever be null?

Update 1:

Before deleting my question because of me being too dumb, just a note on why ReSharper wrote the warning:

I derived my class from IDictionary<TKey, TValue> which seems to be annotated by ReSharper to not have null for the indexer parameter.

Thus, the warning. Sorry for posting such a non-question.

Not sure why ReSharper seems so sure that the expression is always true, since you can pass null to an indexer. However, if you have two indexers that accept reference types, indexing null would be ambiguous unless the null is cast. Perhaps ReSharper doesn't account for the fact that you can still cast null, and so instead assumes that you can never pass null to an indexer, which, again, has been shown to be untrue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM