ExtensionMethod.NET Home of 819 C#, Visual Basic, F# and Javascript extension methods

Get MaxLength attribute from property of an class

Method returns the max length specificed for property

Source

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);

Author: A.Ben

Submitted on: 23 okt 2013

Language: C#

Type: System.Func

Views: 7058