Is the #region directive really useful in .NET?

后端 未结 17 2065
孤城傲影
孤城傲影 2021-01-03 23:43

After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of \"make work\" for the programmer. It\'s w

17条回答
  •  盖世英雄少女心
    2021-01-04 00:28

    There are times when your methods HAVE to be long, especially with web development. In those cases (such as when I've got a gridview with a large, complex object bound to it) I've found it useful to use regions:

    #region Declaring variables for fields and object properties
    
    #region Getting the fields in scope
    
    #region Getting the properties of the object
    
    #region Setting Fields
    

    These are discrete sections of the method that COULD be broken out, but it would be difficult (I'd have to use variables with larger scope than I like or pass a LOT of variables as 'out'), and it is basic plumbing.

    In this case, regions are perfectly acceptable. In others, they are needless.

    I will also use regions to group methods into logical groups. I reject partial classes for this purpose, as I tend to have a lot of pages open when I'm debugging, and the fewer partial classes there are in an object (or page, or dialog), the more of them I can have on my tab list (which I limit to one line so I can see more code).

    Regions are only a problem when used as a crutch, or when they cover poor code (for instance, if you are nesting regions inside of each other within the same scope, it's a bad sign).

提交回复
热议问题