C# Coding Standard – Position of Attribute in relation to Target

attributesccoding-standardscoding-style

I had thought that this was one of the few solved problems in C# coding standards / style; Attributes always appear on the line above the thing to which they are applied a la

[SomeClassAttribute]
class SomeClass
{
   [SomeFieldAttribute]
   bool someField;

   [SomeEnumAttribute]
   SomeEnum
   { 
     SomeValue
   }

   [SomeMethodAttribute]
   void SomeMethod() 
   { 
   }
}

But recently I've started to see Attributes in-line with the thing to which they are applied:

[SomeClassAttribute] class SomeClass
{
   [SomeFieldAttribute] bool someField;

   [SomeEnumAttribute] SomeEnum
   { 
     SomeValue
   }

   [SomeMethodAttribute] void SomeMethod() 
   { 
   }
}

For example on the Microsoft website and in the FileHelpers open source project. Is this just laziness on the part of the author of example code, or something that people actually use on a day to day basis, and if so why?

Best Answer

You can't put the attribute on the line above if it's being applied to a parameter.

e.g. this example from an ASP.NET MVC book

public ViewResult List([DefaultValue(1)] int page)
{
    // ... 
}

Maybe this has led to some people choosing to write attributes inline?

Also another example involving LINQ to SQL mappings..

[Column] public string Name { get; set; }
[Column] public string Description { get; set; }
[Column] public decimal Price { get; set; }
[Column] public string Category { get; set; }

The [Column] attribute almost feels like another modifier like the public access or the type, I can see how it might feel comfortable to write it inline like that.

Related Topic