1

I've created a custom attribute where I want to access the the declaring class of the custom attribute property.

For example:

public class Dec
{
    [MyCustomAttribute]
    public string Bar {get;set;}
}

Here I would like (in the the cass of MyCustomAttribute) to get the type of the declaring class (Dec). Is this by any means possible?

EDIT: Thanks for the replies everyone. I learned something new today.

JensOlsen112
  • 1,279
  • 3
  • 20
  • 26
  • 1
    You know that attributes are instantiated only when you request them, right? See for example: http://stackoverflow.com/questions/12196647/c-sharp-attributes-general-when-are-attributes-instantiated , so when you instantiate them, you clearly have the type of the parent class (because you have to do `type.GetCustomAttributes()` ) – xanatos Feb 19 '15 at 15:10

3 Answers3

3

As I've written, attributes are instantiated only when you request them with type.GetCustomAttributes(), but at that time, you alread have the Type. The only thing you can do is:

[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute 
{
    public void DoSomething(Type t) 
    {

    }
}

public class Dec 
{
    [MyCustomAttribute]
    public string Bar { get; set; }
}

// Start of usage example

Type type = typeof(Dec);
var attributes = type.GetCustomAttributes(true);
var myCustomAttributes = attributes.OfType<MyCustomAttribute>();
// Shorter (no need for the first var attributes line): 
// var myCustomAttributes = Attribute.GetCustomAttributes(type, typeof(MyCustomAttribute), true);


foreach (MyCustomAttribute attr in myCustomAttributes) 
{
    attr.DoSomething(type);
}

so pass the type as a parameter.

xanatos
  • 109,618
  • 12
  • 197
  • 280
1

No, it is not - except for by build-time tools like PostSharp, Roslyn, etc.

You need to find a different approach - perhaps passing a Type in as a constructor argument; or (more likely), but having whatever logic you want to be attribute-based be aware of the declaration context; i.e. assuming MyCustomAttribute has a Foo() method, make it Foo(Type declaringType) or similar.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

This might also work:

class MyCustomAttribute : Attribute
{
    public Type DeclaringType { get; set; }
}

public class Dec
{
    [MyCustomAttribute(DeclaringType=typeof(Dec))]
    public string Bar { get; set; } 
}
Arash.m.h
  • 320
  • 2
  • 11