Question

In C#, when I have different code sections like constants, API functions, helper functions, etc., I would like to divide them. I normally use something like this:

public class Foo {

      //================== Constants ==================
      private const string VIP = "Cob H.";
      private const int IMPORTANT_NUMBER = 23; 

      //================== API Functions ==================
      [WebMethod(MessageName = "SomeInformation")]
      public string SomeInformation() {
            return VIP + " is dead.";
      }

      //================== Inner Classes ==================
      private class IrrelevantClass {
            public string Name { get; set; }
            public string City { get; set; }
      }
}

Is there an elegant way to divide them instead of using a bunch of ugly comments? Like in Objective-C you can use

#pragma mark - Inner Classes

I've looked at all the keywords in the pragma list of C#, and none of them looks promising.

Was it helpful?

Solution

C# has regions which serve a similar function. To use regions, your code would look a bit like this:

public class Foo {

      #region Constants
      private const string VIP = "Cob H.";
      private const int IMPORTANT_NUMBER = 23; 
      #endregion

      #region API Functions
      [WebMethod(MessageName = "SomeInformation")]
      public string SomeInformation() {
            return VIP + " is dead.";
      }
      #endregion

      #region Inner Classes 
      private class IrrelevantClass {
            public string Name { get; set; }
            public string City { get; set; }
      }
      #endregion
}

If you're using Visual Studio, the C# editor allows you to collapse regions, making it easier to browse large source files.

OTHER TIPS

You can use #regions.

#region lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.

public class Foo
{

    #region Constants
    private const string VIP = "Cob H.";
    private const int IMPORTANT_NUMBER = 23;
    #endregion

    //......rest of the code

}

You can use #regions but there are some disadvantages associated with it like people tend to hide dirty code under it or hide some long eye crying method.

I am fine with your approach also but basically write a code in such a way that you don't need to hid under regions.

If you will make it readable then don't need separators at all....

I tried using #region, but I didn't like how using Ctrl + M, O (Collapse to Definitions hotkey) would collapse regions so that I couldn't easily see which functions / members were in each one. I tried using block comments, but those would collapse as well.

I came up with my own high visibility, multi-line separator that doesn't collapse when using Collapse to Definitions. Perhaps someone else will find the idea useful:

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top