Search code examples
c#listdata-annotationsmaxlength

Does MaxLength data annotation work with List<T>?


One can use [MaxLength()] attribute with strings and simple arrays:

i.e.:

[MaxLength(500)]
public string ProductName { get; set; }

Or

[MaxLength(50)]
public string [] Products { get; set; }

But can it be used with a List?

i.e.:

[MaxLength(50)]
public List<string> Types { get; set; }

Solution

  • Looking at the source code, it depends on which .NET version is being used.

    • In .NET framework, it attempts to cast the object as Array. Therefore, if it isn't (e.g., List<T>), an InvalidCastException will be raised. (source)

    • In .NET Core, it calls a method named TryGetCount() which attempts to cast as ICollection and if that fails, it uses reflection to get the Count property. Therefore, it should work on any object that implements ICollection (which List<T> does) or any object with an int Count property. (source)

    Obviously, in both cases, it first checks if the object is a string before going after a collection.

    Note: The same goes for MinLength data annotation.