(C#, .net 6) Why can't I extend the ModelStateDictionary?

88 views Asked by At

I wanted to extend the ModelStateDictionary to add a simple ModelState.AddModelErrors() that accepts multiple errors at once.

I have created the following class:

    public static class ModelStateExtensions
    {
        public static void AddModelErrors(this ModelStateDictionary msd, List<string> errors)
        {
            foreach(var error in errors)
            {
                msd.AddModelError("", error);
            }
        }

        public static void AddDuck(this ModelStateDictionary msd)
        {
            msd.AddModelError("duck", "quack");
        }
    }

I then attempt to call it in the controller like so:

if(errors.Any())
            {
                ModelState.AddModelErrors(errors);

            }

And get the following error message:

'ModelStateDictionary' does not contain a definition for 'AddModelErrors' and the best extension method overload 'ModelStateExtensions.AddModelErrors(ModelStateDictionary, List<string>)' requires a receiver of type 'ModelStateDictionary'

I have:

  • Added a using statement with the proper namespace to the controller
  • Compiled everything first
  • The extension method is in the same project, so a project reference shouldn't be needed

Regardless, I think those would give me a different error message, right?

What does that error message mean? How is the receiver not of type ModelStateDictionary?

0

There are 0 answers