Get the default name value of an attribute and a specific property - CSharp System

CSharp examples for System:Attribute

Description

Get the default name value of an attribute and a specific property

Demo Code


using System.Collections.Generic;
using System;/* www  .  j av  a  2s  .  co  m*/

public class Main{
        /// <summary>
        /// Get the default name value of an attribute and a specific property
        /// </summary>
        /// <param name="attribute">attribute from where to get the default value</param>
        /// <param name="propertyName">property to get the default value</param>
        /// <returns></returns>
        public static object GetDefaultValue(Attribute attribute, string propertyName)
        {
            Type attributeType = attribute.GetType();
            try
            {
                var property = attributeType.GetProperty(propertyName);
                if (property == null)
                    return null;
                var instance = Activator.CreateInstance(attributeType);

                return property.GetValue(instance, null);
            }
            catch (Exception)
            {
                return null;
            }
        }
}

Related Tutorials