Naming conventions and guidelines for custom attributes - c#

Are there any conventions (perhaps by Microsoft) on attributes if their name should be singular or plural?
I'm not sure what the naming conventations are or if there are any at all? I want an attribute for the roles in my system I'm not sure whether by convention (if any) I should pluralize it to RolesAttribute or keep it singular RoleAttribute.
- Edit -
Now I think of it custom attributes are still classes that derive from the Attribute base class, so would the conventions of classes apply to C# attributes as well?

It really depends on the functionality you are implementing. In short, if you are assigning one role using your attribute then keep it singular, if you are assigning multiple roles then make it plural.
In more general terms, Attributes should be named using clear pascal cased names and their function is to associate metadata, or declarative information with code. As with everything else in your code, make sure that they are descriptive and unambiguous.
Some good guidelines I like to follow are the following:
Avoid unsealed attributes
Custom attributes should end with the suffix Attribute
Define constructors which have parameters to intialize properties corresponding to the required arguments
Each constructor parameter should have the same name (apart from the casing) as the corresponding property
Define accessors for attribute parameters, usually settable properties for optional parameters and getter only for required parameters
Mark attributes with the AttributeUsageAttribute

Related

Create a custom attribute that would hint to Resharper that property is used implicitly

If I define a class with a public property that is not used explicitly, but annotate it with either Newtonsoft.Json.JsonProperty or JetBrains.Annotations.UsedImplicitly, then I won't get any usage warnings.
Can I define such custom attribute? My motivation is that I already have some custom attributes to mark such properties and adding this feature on top of them would save some redundant annotations.
According to the Resharper Documentation you should be able to apply a MeansImplicitUseAttribute to your own attribute's definition.
MeansImplicitUseAttribute
Should be used on attributes so that symbols marked with such attributes are not reported as unused. The marked attribute behaves the same as UsedImplicitlyAttribute.

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.
No. You will have to apply the [SameAttribute] to each field individually.
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.
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.
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

Custom vs. non-custom attributes?

Something which implements the ICustomAttributeProvider interface will allow you to get custom attributes that have been applied to it via the GetCustomAttributes method. As I understand it, a custom attribute is basically a special class (ending in "Attribute" and extending the Attribute class) that is created to be applied to something like a method or class using the appropriate syntax ([FooAttribute] just before the method/class/etc. in C#, for example). But if that is a custom attribute, what is a non-custom attribute? I used to think that attributes that were bundled with .NET were non-custom, but GetCustomAttributes even returns me attributes like System.ThreadStaticAttribute, which are very core to the .NET framework.
Is there such a thing as a non-custom attribute, or is "custom attribute" just a tautology?
Everything that derives from Attribute is a custom attribute.
"Attribute" is a generic term. Objects in the real world have innumerable attributes. Classes, members and parameters all have attributes that we can describe -- names, types, accessors, number of members, inheritance information, etc.
Custom attributes are things that we tack on -- aspects that we want to associate and use to describe, but which are not intrinsic.
I don't know if the following has any relevance, but if you say
var a = typeof(string).Attributes;
you get a value of a flags enum type called TypeAttributes. Maybe these flags are the "non-custom" attributes of the type?
See Wikipedia, quoting:
Developers can add metadata to their code through attributes. There
are two types of attributes, custom and pseudo custom attributes, and
to the developer these have the same syntax. Attributes in code are
messages to the compiler to generate metadata. In CIL, metadata such
as inheritance modifiers, scope modifiers, and almost anything that
isn't either opcodes or streams, are also referred to as attributes.
See also the CLI specification about extending metadata, where references are found to the term "custom" attributes (e.g. I.9.7 in http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-335.pdf)

What's with using C# attributes with the 'Attribute' suffix?

I'm looking at some C# code that applies several LINQ to SQL attributes with the Attribute suffix, e.g. ColumnAttribute, instead of the plain Column that I am used to using. Is there any reason but verbosity to do this?
There is no semantic difference. Probably whoever wrote the code just preferred that notation.
It's also possible that the code was automatically generated using a tool. Code generation tools usually don't bother to strip the Attribute bit from the attribute's type name.
Most attributes end with the word Attribute, including ColumnAttribute, CLSCompliantAttribute, and SerializableAttribute. The compiler allows the last word Attribute to be omitted. It's the programmer's choice whether to add Attribute to such names or not.
The Attribute suffix, however, is merely a convention: it is perfectly valid, albeit unusual, to define an attribute, for example, as follows:
[AttributeUsage(AttributeTargets.All)]
public class Foo : Attribute {
}
just as it is to define an exception named Throwable, for example.
The attribute is called ColumnAttribute. The compiler just provides syntactic-sugar to allow you to specify them without the Attribute suffix.
There's no practical difference.
No, it's just a style decision. However, if what you're looking at is code generated using CodeDOM the presence of the suffix is expected since C# code generator will keep the full ___Attribute type name when adding an attribute.
They're syntactically the same. AFAIK there's no reason to do this unless the person in question wasn't familiar with the fact that syntax sugar in C# adds the 'Attribute' suffix automatically when adding an attribute via square brackets.
Column is simply the nickname of ColumnAttribute, and syntactically identical in functionality, and allowed by the compiler in either form.
Some people prefer to use the full name, out of habit of following the Framework Naming Guidelines, which encourage adding Attribute to custom attribute classes, or I to interface types.
If you look at the Philips Healthcare - C# Coding Standard, rule 3#122, you can see they actually want coders to add the suffix "Attribute" to attributes.
http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf
The code may be generated but the author(s) of the code generator are probably trying to create code that meets as many standards as possible.

Meaning of text between square brackets

I have seen a lot of C# programs that use the [], for example [STAThread] and then the code follows. Another classic example is [DLLImport].
I know what STAThread means but my question is what is the significance of the square brackets, essentially what do they tell the compiler?
It's an attribute. Attributes are a form of metadata that you can attach to various code elements: classes, methods, assemblies etc.
Some attributes have special meaning to the C# compiler, for instance the [Serializable] probably tells the compiler to emit some code that can serialize an instance of the class (I say 'probably' since I do not know the inner workings of the C# compiler).
You can also create your own attributes (by inheriting System.Attribute). Using reflection you could then at run-time extract information from the attributes.
A simple example would be to create an attribute to specify what kind of input field to use in a HTML form when displaying an object's property.
Some links:
Book chapter on attributes
Attributes overview (MSDN)
https://stackoverflow.com/search?q=C%23+attributes
http://www.google.com/search?q=C%23+attributes
These are attributes.
Attributes have many uses - [Obsolete] marks a method as obsolete and the compiler will warn you. Others like [DebuggerNonUserCode] tell nothing to the compiler and are there to let the debugger know that the code in the marked method is auto-generated.
You can also create your own attributes and use them to mark any kind of metadata. For example, your Customer object might have an attribute [MarketingInformation("Customer is rich! Milk him good!")].
See here for info about attributes in .Net:
http://msdn.microsoft.com/en-us/library/5x6cd29c.aspx
They are attributes, that add meta data to whatever they are decorating.
Theses are called code attributes. Attributes are used to mark code with properties which are usually designed to specify behavior during execution. They are commonly used to mark methods, properties and parameters. During execution of your code something called "reflection" will be performed to examine the code. Reflection tells the compiler to observe and obey any instructions specified by you as the coder marking attributes against the code.
A good example would be the [Serializable] attribute. This attribute when marked above a class indicates to the compiler that it can be serialized for the purposes of persisting the class instance or for transmitting across a medium such as SOAP web services.
See the following article:
link text

Categories