Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a C# attribute to many fields [duplicate]

Tags:

c#

Suppose I have a minimal C# class that looks like the following:

class Thing
{
    private float a, b, c, d;
    (...)
}

Is there a way that I can apply an attribute to all four fields without having to write it out four times? If I put [SomeAttribute] in front of the private, it appears to apply to a only.

like image 836
peterpi Avatar asked Jan 13 '23 13:01

peterpi


2 Answers

class Thing
{
    [SomeAttribute]
    public float a, b, c, d;
}

The above, which you proposed, would work how you expect it to work. You can test this:

[AttributeUsage(AttributeTargets.Field)]
sealed class SomeAttribute: Attribute
{
    public SomeAttribute()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        var t = typeof(Thing);
        var attrs = from f in t.GetFields()
                    from a in f.GetCustomAttributes()
                    select new { Name = f.Name, Attribute = a.GetType() };

        foreach (var a in attrs)
            Console.WriteLine(a.Name + ": " + a.Attribute);

        Console.ReadLine();
    }
}

It prints:

a: SomeAttribute
b: SomeAttribute
c: SomeAttribute
d: SomeAttribute
like image 171
Daniel A.A. Pelsmaeker Avatar answered Jan 17 '23 18:01

Daniel A.A. Pelsmaeker


Yes, it's possible:

[SomeAttribute]
public int m_nVar1, m_nVar2;

(but obviously only if the types are the same)

REFERENCE

Example:

[ContextStatic]
private float a, b, c, d;
like image 21
andy Avatar answered Jan 17 '23 18:01

andy