Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
like image 296
anastaciu Avatar asked Dec 30 '22 15:12

anastaciu


1 Answers

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.

like image 74
41686d6564 stands w. Palestine Avatar answered Jan 08 '23 05:01

41686d6564 stands w. Palestine