C# variable naming

15 Jan

From working in a team environment, I have learnt of a number of different ways of naming variables. Reading this post it could be thought that variable naming schemes are purely preference, however I believe that there are some arguments against certain schemes. Take for example:

        private String str;

        public void Method1(String str)

        {

            this.str = str;

        }

 

If you use a plugin called Resharper  like I do then the method input is highlighted because it hides str. I have more of an issue with the following potential mistake:

        private String str;

        public void Method1()

        {

            this.str = str;

        }

 

The previous code is still valid with the compiler, however it is clear that str is not going to be populated, however a tool such as resharper will not make you aware that the this.str is never assigned.

The approach that I use for code sample 1 would be:

        private String _str;

        public void Method1(String str)

        {

            _str = str;

        }

 

The underscore ‘_’ is used for member/class wide variables. If we are to replicate code sample 2 with the underscore naming scheme we will get the following result:

        private String _str;

        public void Method1()

        {

            _str = str;

        }

We can clearly see that this code will not compile. We can also observe that the underscore notation is more compact by not requiring the ‘this’ keyword.

Another two reasons I like the underscore naming convention are:

 

  1. Intellisense grouping. Press underscore key and intellisense will group all member variables together.

  2. No confusion as to the availability of a variable. If it has underscore it is available class-wide. If it doesn’t it is only available within that method.

I have seen other people use m_VariableName but I think that just using an underscore is better because it is shorter, and the intellisense is grouped better because it is at the start of the intellisense list. Another alternative naming scheme involves putting the type in the variable name. I would advice against this because tools like resharper can tell a user what type a variable is in design time, and implicit typing will likely destroy the naming scheme.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: