سؤال

I have the indexer and want to check if is it not null, and if it is then throw ArgumentNullException, but Gendarme sets the warning

InstantiateArgumentExceptionCorrectlyRule: This method throws ArgumentException (or derived) exceptions without specifying an existing parameter name. This can hide useful information to developers.Fix the exception parameters to use the correct parameter name (or make sure the parameters are in the right order).

public override LocalizedString this[string key]
{
    get
    {
        if (key == null)
        {
            throw new ArgumentNullException("key");
        }
        return base[key];
    }
    set
    {
        if (key == null || value == null)
        {
            throw new ArgumentNullException("key");
        }
        base[key] = value;
    }
}

How can I fix my indexer?

هل كانت مفيدة؟

المحلول

Well, it's definitely not right at the moment. Look at this:

if (key == null || value == null)
{
    throw new ArgumentNullException("key");
}

That means it will throw an exception claiming "key" is null when it should actually be "value".

So the code should look like this:

if (key == null)
{
    throw new ArgumentNullException("key");
}
if (value == null)
{
    throw new ArgumentNullException("value");
}

I don't know whether that will fix the warning or not, but it would be the correct code.

This bug report suggests this is a bug in Gendarme which hasn't been fixed. If you can explicitly disable the warning just for that indexer, that's probably the best way to go. (I haven't used Gendarme so I don't know whether or not that's feasible, but it's worth looking into.)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top