C#: code style - places for members [closed]
I know that private fields are first. Where should be placed other members according to C# code-style?
I mean: private/protected/internal/public fields/properties/methods/events. I always placed events at the last part of class. I sometimes place private method near public property that use it. I don't think it is right location, but i can't choose the place for it and for a lot of other members.
According to StyleCop (the style checker made by Microsoft), the correct ordering is:
Adjacent elements of the same type must be positioned in the following order by access level:
- public
- internal
- protected internal
- protected
- private
- Rule SA1202
You might also be interested in rule SA1201, which deals with the order of the types of elements (ie. Fields go first, then constructors, ...).
To read more about the StyleCop Rules Guide go here: http://stylecop.codeplex.com/releases/view/44839
This is an example of coding guidelines (see towards the end, "File organization"). There are many and not all agree on the order of class members.
As a matter of personal preference, I prefer grouping constants, fields, properties, constructors, members (public first, then internal, then protected, then private) in this order using #region - #endregion blocks.
The reason why I leave private members for last is that when I read code, I like to get the information of the class's interface to the outside world before knowing how it implements it in private members.
Classes should be organized into regions within an application using a layout determined
by your application architect. These may be based on accessibility, type, or functionality. Consult your architect for the layout strategy used in your application.
Example:
// Class layout based on accessibility
class Purchasing
{
#region Main
#region Public
#region Internal
#region Protected
#region Private
#region Extern
#region Designer Generated Code
}
Guidelines:
o Use the same layout consistently in all classes in an application.
o Omit regions if their associated class elements are not needed.
o The Designer Generated Code region created by Visual Studio’s Visual Designer should never be modified by hand. It should contain only code generated by the designer.
I prefer
- private
- protected
- public
I think there isn't much you can do wrong in that kind of code style.
Do what ever feels right for you - just be consistent.
I think that, unless you make a mess of your code messing everything and putting it all together, you can choose which order you prefer.
As long as you are consistent with it, there is no correct order.
精彩评论