Get MaxLength attribute from property of an class

 public static class AttributesExtensions
    {
        public static int GetMaxLength<TSource, TProperty>(this TSource source, Expression<Func<TSource, TProperty>> propertyLambda)
            where TSource : class, new()
            where TProperty : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
        {
            PropertyInfo propInfo = source.GetPropertyInfo(propertyLambda);
            MaxlengthAttribute attrMaxLength = propInfo.GetCustomAttributes(typeof(MaxlengthAttribute), false).FirstOrDefault() as MaxlengthAttribute;
            return attrMaxLength != null ? attrMaxLength.MaxLength : 0;
        }
    }
Example:
usage :
public class Examp
{
[MaxLength(10)]
public string Nume {get;set;}

public int virsta{get;set;}

}
retriving it
examp e = new examp();
int max = e.GetMaxLength(x=>x.Nume);

Description

Method returns the max length specificed for property

Details

  • Author: A.Ben
  • Submitted on: 10/23/2013 7:54:35 AM
  • Language: C#
  • Type: System.Func
  • Views: 2904

Double click on the code to select all.

 

;