Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming conventions in C# - Global Variables [closed]

I know there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)

Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.

Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.

I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!

It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.

So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).

like image 440
Dave Avatar asked Jan 25 '13 12:01

Dave


2 Answers

Just use the class name in the same way you'd use "this", in a static class. Example follows:

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 actually think of any other way to do it.

like image 193
Alex Avatar answered Nov 19 '22 09:11

Alex


By global variables, I assume you mean const or static fields

I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.

Also, you can configure Resharper to play nicely with StyleCop.

like image 35
Ergwun Avatar answered Nov 19 '22 08:11

Ergwun