简体   繁体   中英

Does MaxLength data annotation work with List<T>?

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

ie :

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

Or

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

But can it be used with a List?

ie :

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

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 (eg, 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 .

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