0

In all of the tutorials out there for custom attributes they teach us how to create and define custom attributes which is no more than simple comment about the class/method. I am trying to figure out how can I read from those custom attributes in .NET inside some method. For example:

[SomeCustomAttr(param1, param2)]
public void Method1()
{
   read param1 from here
   read param2 from here
}

There are really great frameworks out there which do work with the entered data. Does anyone can give me some direction how to deal with this problem ?

Gabriel kotev
  • 369
  • 3
  • 15
  • Note that `param1` and `param2` are just parameters to the `SomeCustomAttr` constructor. Assuming that your ctor assigns those values to properties, you would just follow the information from that question, and access the two properties after getting the attribute object. – Jonathon Reinhart Dec 09 '13 at 08:45

2 Answers2

4

Assuming that the parameters you refer to are properties of the custom attribute class:

class Program
{
    static void Main(string[] args) {
        Test();
        Console.Read();
    }

    [Custom(Foo = "yup", Bar = 42)]
    static void Test() {
        // Get the MethodBase for this method
        var thismethod = MethodBase.GetCurrentMethod();

        // Get all of the attributes that derive from CustomAttribute
        var attrs = thismethod.GetCustomAttributes(typeof(CustomAttribute), true);

        // Assume that there is just one of these attributes
        var attr1 = (CustomAttribute)attrs.Single();

        // Print the two properties of the attribute
        Console.WriteLine("Foo = {0},  Bar = {1}", attr1.Foo, attr1.Bar);
    }
}

class CustomAttribute : Attribute
{
    public string Foo { get; set; }
    public int Bar { get; set; }
}

Note that attributes are a little special, in that they can take named parameters (which correspond to public property names), without declaring any constructor.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

Reflection is the right way to get the attribute.

            var TypeObj = typeof(Type1);
            var MethodInfoObj = TypeObj.GetMethod("Method1");

           // var AllAttributes= MethodInfoObj.GetCustomAttributes(true);

            var Attributes = MethodInfoObj.GetCustomAttributes(typeof(SomeCustomAttr), true);
            if (Attributes.Length > 0)
            {
                var AttributeObj = Attributes[0] as SomeCustomAttr;
                var value_param1  = AttributeObj.param1 ;
            }
Priyank
  • 1,353
  • 9
  • 13
  • 1
    A few pieces of advice: 1) Don't use `UpperCamelCase` for variable names (e.g. `TypeObj`) - C# convention uses that for class names. 2) If you use `as`, you should really check for `null`. 3) I'm sure this was a snippet from somewhere, but it'd still be nice if you indented it properly, to make it easier to read. – Jonathon Reinhart Dec 10 '13 at 00:54