Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Reflection for finding deprecation

Tags:

c#

t4

I am curious if anyone has written any code to reflect into a class and find its Deprecated methods?

Ive whipped a T4 Template for reactive and would love to have it stop generating handlers for deprecated events, any clever hackers out there that already beat me to the punch?

like image 957
Jake Kalstad Avatar asked Feb 08 '11 21:02

Jake Kalstad


1 Answers

I don't know if you're asking for t4 framework or not but here's a generic reflection sample for Obsolete flagged methods.

class TestClass
{
    public TestClass()
    {
        DeprecatedTester.FindDeprecatedMethods(this.GetType());
    }

    [Obsolete("SomeDeprecatedMethod is deprecated, use SomeNewMethod instead.")]
    public void SomeDeprecatedMethod() { }

    [Obsolete("YetAnotherDeprecatedMethod is deprecated, use SomeNewMethod instead.")]
    public void YetAnotherDeprecatedMethod() { }

    public void SomeNewMethod() { }        
}

public class DeprecatedTester
{
    public static void FindDeprecatedMethods(Type t)
    {
        MethodInfo[] methodInfos = t.GetMethods();

        foreach (MethodInfo methodInfo in methodInfos)
        {
            object[] attributes = methodInfo.GetCustomAttributes(false);

            foreach (ObsoleteAttribute attribute in attributes.OfType<ObsoleteAttribute>())
            {
                Console.WriteLine("Found deprecated method: {0} [{1}]", methodInfo.Name, attribute.Message);
            }
        }
    }
}
like image 121
HuseyinUslu Avatar answered Sep 20 '22 00:09

HuseyinUslu