Search code examples
c#c#-4.0getcustomattributesconditional-attribute

Getting a specific attribute instance using ConditionString


This might be a silly question. I am trying to understand the concept of conditional attribute.My aim is to get a specific attribute instance and ended up in getting NullReferenceException instead of the output "CONDITION1".

class Program
    {
    private static void Main(string[] args)
    {
        //Getting a specific attribute instance
        ConditionalAttribute conditionalAttribute =
            (ConditionalAttribute) Attribute.GetCustomAttribute(typeof (Class1), typeof (ConditionalAttribute));
        string condition = conditionalAttribute.ConditionString;
        Console.WriteLine(condition);
        Console.ReadLine();
    }

    public class Class1
    {
        [Conditional("CONDITION1"), Conditional("CONDITION2")]
        private static void MyMethod()
        {
            Console.WriteLine("Mymethod");
        }
    }

    }

I hope i am using right attributes in the GetCustomAttribute. Can someone point out where is the mistake?

Thanks in advance.


Solution

  • Your class don't have Conditional attribute,your method marked with Conditional Attribute.So you need to get your Method first,then get the Attribute(s)

    var attributes = typeof(Class1)
                    .GetMethod("MyMethod", BindingFlags.NonPublic | BindingFlags.Static)
                    .GetCustomAttributes().OfType<ConditionalAttribute>()
                    .OrderBy(a => a.ConditionString);
    foreach (var at in attributes)
    {
         Console.Write(at.ConditionString);
    }