Max Yankov
Max Yankov

Reputation: 13337

A lot of fields with the same attribute

I find myself writing a lot of this kind of stuff:

[SameAttribute]
ClassA fieldA;

[SameAttribute]
ClassB fieldB;

[SameAttribute]
ClassC fieldC;

...

Is there a syntax in C# that would allow me to mark several fields with the same attribute at once? May be there are coding conventions about this situation that would make this code less verbose and more readable?

Edit: Just to clarify, I don't want every field of the class to have this attribute, there's just a lot of them.

Upvotes: 1

Views: 123

Answers (4)

MgSam
MgSam

Reputation: 12813

In addition to the other answers above, PostSharp, which allows "aspect-oriented programming" lets you define attributes that will apply to each member in a class. You can use it to make a custom attribute that would apply your desired attribute to all of the members.

Upvotes: 1

Anthony Shaw
Anthony Shaw

Reputation: 8166

There is nothing out of the box, that I know of, but you could use a Visual Studio add-in like ReSharper to create a live template to automatically add the Attribute you wish to use when you use a certain template

http://www.jetbrains.com/resharper/features/code_templates.html

Upvotes: 0

Jason Watkins
Jason Watkins

Reputation: 3785

If you want SomeAttribute to apply to all fields in a class, it might be possible to apply the attribute to the entire class. However, even if SomeAttribute is allowed to target classes, its exact behavior when doing so is dependent on the implementation of SomeAttribute. Otherwise no, you have to apply the attribute to each field individually.

Upvotes: 1

p.s.w.g
p.s.w.g

Reputation: 149108

No. You will have to apply the [SameAttribute] to each field individually.

Upvotes: 1

Related Questions