What's the best way to layout a C# class? [duplicate]
Asked Answered
H

10

49

Is there a standard way of laying out a C# file? As in, Fields, then Properties, then Constructors, etc?

Here's what I normally do, but I'm wondering if there's a standard way?

  1. Nested Classes or Enums
  2. Fields
  3. Properties
  4. Events
  5. Constructors
  6. Public Methods
  7. Private Methods

Do people group their fields together, or do they put them with the properties? Or do people not worry about an order? Visual Studio seems to make it so hard to do.

Edit: Moved other part about ReSharper here: Make Resharper respect your preference for code order.

Hairless answered 2/3, 2009 at 20:1 Comment(1)
You can use XArrange 2012, it is free. Download available at : visualstudiogallery.msdn.microsoft.com/… Method, property etc sorting is possible...Applicator
R
66

I tend to use Microsoft StyleCop, which has a set order according to rule SA1201:

Cause An element within a C# code file is out of order in relation to the other elements in the code.

Rule Description A violation of this rule occurs when the code elements within a file do not follow a standard ordering scheme.

To comply with this rule, elements at the file root level or within a namespace must be positioned in the following order:

  • Extern Alias Directives
  • Using Directives
  • Namespaces
  • Delegates
  • Enums
  • Interfaces
  • Structs
  • Classes

Within a class, struct, or interface, elements must be positioned in the following order:

  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes

Complying with a standard ordering scheme based on element type can increase the readability and maintainability of the file and encourage code reuse.

When implementing an interface, it is sometimes desirable to group all members of the interface next to one another. This will sometimes require violating this rule, if the interface contains elements of different types. This problem can be solved through the use of partial classes.

  1. Add the partial attribute to the class, if the class is not already partial.

  2. Add a second partial class with the same name. It is possible to place this in the same file, just below the original class, or within a second file.

  3. Move the interface inheritance and all members of the interface implementation to the second part of the class.

Runoff answered 10/3, 2009 at 13:53 Comment(2)
Unfortunately StyleCop also has additional ordering rules that affect this structure as well. For instance, it recommends that static members all be grouped together.Fireman
I personally consider that to be a good thing... but I can certainly understand arguments against.Runoff
U
10

I think there's no best way. There are two important things to consider when it comes to layout. The first most important thing is consistency. Pick an approach and make sure that the entire team agrees and applies the layout. Secondly, if your class gets big enough that you are searching for where those pesky properties live (or have to implement regions to make them easier to find), then your class is probably too large. Consider sniffing it, and refactoring based on what you smell.

To answer the reshaper question, check under Type Members Layout in Options (under the C# node). It's not simple, but it is possible to change the layout order.

Unaccountable answered 2/3, 2009 at 20:7 Comment(3)
Thanks, sorry I moved the resharper part of the question based on JaredPar's feedback. Post your 2nd part of the answer there and I'll give you another up vote.Hairless
Regions are also about introducing a consistent structure (especially in this context).Fireman
@scott agreed, but they become much more necessary as class file sizes get larger. The progression of badness is: 1) no regions, 2) regions, 3) partial classesUnaccountable
R
3

I don't believe regions are necessarily a sign of bad code. But to determine that you will have to review what you have. As I've stated here this is how I regionize my code.


Enumerations
Declarations
Constructors
Methods
Event Handlers
Properties

But the main thing is keeping it consistent and purposeful.

Rixdollar answered 2/3, 2009 at 20:11 Comment(3)
I see (big) regions mainly as an indicator to use partial classes in multiple files. A common example is putting all data in one file and algorithms in another. That also paves the way for splitting the class down the line.Attendance
I love to see events-properties duo come above methods :)Ideality
@DavidSchmitt: (I realise this post is quite old, but..) wouldn't a large region (or class) be more an indicator of code refactoring?Patronage
M
1

I tend to clump private data and tend to clump related methods/properties in functional groups.

public class Whatever {
   // private data here
   int _someVal = kSomeConstant;

   // constructor(s)
   public Whatever() { }

#region FabulousTrick  // sometimes regionize it
   // fabulous trick code
   private int SupportMethodOne() { }
   private double SupportMethodTwo() { }
   public void PerformFabulousTrick(Dog spot) {
       int herrings = SupportMethodOne();
       double pieces = SupportMethodTwo();
       // etc
   }
#endregion FabulousTrick
   // etc
}
Minneapolis answered 2/3, 2009 at 20:11 Comment(0)
I
1

You can try Regionerate to help with this. I really like it and it's a Scott Hanselman pick.

Ichthyolite answered 1/6, 2009 at 20:18 Comment(0)
T
1

As said, I don't think there is a best way as such. But some organisation does help you the programmer.

How often in a long project have you spent time going up and down one or more source files trying to find one of your functions.

So I make use of the #region a lot to in this sort of way -

  1. region Events : All of the event references that this class uses (at least in this particular partial class).

  2. region Controls : All functions that directly interact with controls on a form.

  3. region MDI : set the mdi up

    Then there will be some to do with functionality rather than interface,

  4. region Regex searches

I sort of make it up as I go along, but using the same pattern I always use. I must say I have been told by some programmers picking up my work that it is easy to follow and others that its messy.

You can please half the people half the time and the other half a quarter of the time and the other quarter of the time you confuse everyone including yourself. I think Winston Chrchil said that.

Tetrapody answered 17/4, 2011 at 14:56 Comment(0)
B
0

Whatever makes your more productive. Some like private fields next to property accessors, some like fields together above the constructors. The biggest thing that can help is grouping "like," elements. I personally like bringing together private methods, private properties, etc.

Try some things out and again, whatever you feel makes you more productive and helps you keep your code maintained.

Beverleebeverley answered 2/3, 2009 at 20:11 Comment(0)
R
0

Each to their own, but I tend to follow the same order that the MSDN help follows.

I also don't like to nest classes or enums, instead create separate files for them, that also makes writing unit tests easier (since it's easy to find the associated test file when you need to add/fix/refactor a test).

IMHO the order isn't that important because VS makes it very easy to find all members (especially if you follow the one class/interface/enum per file approach), and Sandcastle will group them if you want to build docs, so I'd be more concerned about giving them meaningful names.

Rabon answered 2/3, 2009 at 20:13 Comment(2)
Order is still important because it introduces consistency. By always following the same layout in all of your classes it becomes easier to locate things.Fireman
That's my point about VS, if you're navigating through the source rather than through the Members drop-down list, then for any non-trivial class, you're wasting time. Bookmarks also speed up development switching between members and/or types. Agree on consistency, which is why I follow MSDN order:)Rabon
T
0

On top of keeping a consistent set of regions in your class files, I keep all components of a region in alphabetical order. I tend to have a bit of "visual memory" when it comes to reading code and it drives me crazy having to use the navigation dropdown to find code in a file because it's all over the place.

Teatime answered 10/3, 2009 at 19:57 Comment(0)
F
0

I use the following layout:

events globals/class-wide fields private/internal properties methods public/protected properties methods nested classes (although I try to avoid these whenever possible)

I also firmly believe in 1 code "thing" (class, interface, or enum) per file, with the file name the same as the "thing" name. Yes, it makes a larger project but it makes it infinately easier to find things.

Fireman answered 10/3, 2009 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.