C # naming conventions - global variables

I know there is a discussion / opinion about using a keyword thisor underscore regarding private fields / properties (and I mentioned that I'm stuck on .NET 2.0)

Personally, I prefer this, but sometimes you cannot use it, for example, when you need to refer to a global variable from a static method. Well, then we are forced to use underscores (if we have only 2 options, thisor underscores). This means that if my class uses any static methods, I cannot use it thisthroughout the document.

Now I read the naming rules and used StyleCop , both would prefer that I don't use underscores, but my Resharper pretty much insists on using _.

I don’t think it is right for one class to use _ and the next class, thisjust to use it when classes mix non-static and static methods! The tip here on SO is to stick with one implementation / style, but I don't know if that means I should ignore Microsoft (and I know that MS doesn't always stick to its rules)!

A prefix was suggested with something else similar to Hungarian, but a prefix with globVariableName, where glob points to global. I hate this idea, it is too imposed and will not be obvious to any other developer outside my team.

So my question is: what is the best way to define global variables? Since they are guiding names, maybe I can just ignore it (at least you can use it sequentially, but it’s incorrect to ignore advice from the creators of the language).

+5
source share
4 answers

Just use the class name just like you use "this" in a static class. Example:

public static class MyStatic
{
    public static object Global;

    public static void SomeMethod()
    {
        var theGlobal = MyStatic.Global;
    }
}

public class MyNonStatic
{
    public object Global;

    public void SomeMethod()
    {
        var theGlobal = this.Global;
    }
}

Note. I can’t think of another way to do this.

+2
source

, const static

, StyleCop ClassName.staticField static const, , , . , .

, Resharper, StyleCop.

+1

;

  • , this ; . , - DI, - , .

    public void SomeMethod(int someVariable)
    {
        this.someVariable = someVariable;
    }
    
  • this ; ; , , .

  • I call static variables in the same way as I call class variables; using a keyword thisreduces the risk of confusion between private and static variables.

0
source

I always use the underscore for both static and instance variables.

For example, the variables I use this.variable

For variables statici, sometimes their prefix with the class name, for example,ClassName.variable

0
source

All Articles