Chris Rau
Chris Rau

Reputation: 13

Custom Attributes created inside generic Class

public sealed class test<T> : IEnumerable<T> where T : new()
{
     public sealed class Ignore : Attribute { }
}    

public class test_2
{
     [ ???? ]
     string helllo;
}

Is there a way to access the Attribute from outside the test<T> class? I can't seem to find one.

Upvotes: 1

Views: 277

Answers (1)

Bogdan Beda
Bogdan Beda

Reputation: 788

C# does not support Generic Attributes. I know your attribute is not generic but I suppose you want it inside that generic class to use T in attribute level, which makes the Attribute generic (You'll get different Ignore type for each T)

Unfortunately you can't achieve this in C#. Why does C# forbid generic attribute types?

Updated from comments: You can have the Ignore attribute in the scope of the namespace. The you can do reflection on test<T> and look for properties with Ignore attribute.

public sealed class Ignore : Attribute { }

public sealed class test<T> : IEnumerable<T> where T : new()
{
    [Ignore]
    public test_2 SomeProperty { get; set; }
}


public class test_2
{
    [Ignore]
    public string TestData { get; set; }
}

Upvotes: 1

Related Questions