0

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.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
Dev
  • 1,451
  • 20
  • 30

1 Answers1

1

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);
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • @Rashmi your method is private I think that is the problem.I have updated my answer try again – Selman Genç Feb 01 '14 at 16:13
  • Yes, you are right. Method was private. Thanks for pointing out and helping me to understand the topic. It prints the output in reverse order: CONDITION2CONDITION1 – Dev Feb 01 '14 at 16:18
  • @Rashmi you can easily use OrdeyBy method, `OrderBy(a => a.ConditionString)` – Selman Genç Feb 01 '14 at 16:25
  • Yeah, can use OrderBy to solve this. I was interested in knowing why "attributes" variable is storing values in reverse order.(Why on stack?) – Dev Feb 01 '14 at 16:31
  • I tried,and I get this output without using orderby: `"CONDITION1 CONDITON2"` – Selman Genç Feb 01 '14 at 17:01
  • Without orderby, it is CONDITION2CONDITION1. class Program { static void Main(string[] args) { var attributes = typeof(Class1).GetMethod("MyMethod").GetCustomAttributes(); foreach (var at in attributes) {Console.Write(at.ConditionString);} Console.ReadLine(); } } public class Class1 { [Conditional("CONDITION1"), Conditional("CONDITION2")] public static void MyMethod() { Console.WriteLine("Mymethod"); } } – Dev Feb 01 '14 at 21:16