Get a custom attribute applied to a member of a type.
using System;
using System.Reflection;
public class TestClass
{
[Obsolete("This method is obsolete. Use Method2 instead.")]
public void Method1()
{}
public void Method2()
{}
}
public class DemoClass
{
static void Main(string[] args)
{
Type clsType = typeof(TestClass);
MethodInfo mInfo = clsType.GetMethod("Method1");
bool isDef = Attribute.IsDefined(mInfo, typeof(ObsoleteAttribute));
Console.WriteLine("The Obsolete Attribute {0} defined for {1} of class {2}.",isDef ? "is" : "is not", mInfo.Name, clsType.Name);
if (isDef)
{
ObsoleteAttribute obsAttr = (ObsoleteAttribute)Attribute.GetCustomAttribute( mInfo, typeof(ObsoleteAttribute));
if (obsAttr != null)
Console.WriteLine("The message is: \"{0}\".",obsAttr.Message);
}
}
}
Related examples in the same category