Search code examples
c#custom-attributeslate-binding

check method for custom attribute


I'm not sure why the below method always returns false

        // method to check for presence of TestCaseAttribute
    private static bool hasTestCaseAttribute(MemberInfo m)
    {
        foreach (object att in m.GetCustomAttributes(true))
        {
            Console.WriteLine(att.ToString());
            if (att is TestCase.TestCaseAttribute) // also tried if (att is TestCaseAttribute)
            {
                return true;
            }
        }
        return false;

    }

even though the console output looks like this:

TestCase.DateAttribute
TestCase.AuthorAttribute
TestCase.TestCaseAttribute

What am I missing here?

Edit; this approach seems to work...

  private static bool hasTestCaseAttribute(MemberInfo m)
    {
        if (m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any())
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Solution

  • This should do the trick.

        private static bool hasTestCaseAttribute(MemberInfo m)
        {
            return m.GetCustomAttributes(typeof(TestCaseAttribute), true).Any();
        }