Stop Use VAR Everywhere and Think before Use Underscore with Private Variable in C#

0
25

Be a Thinker First, Then Doer

Readers of the Topic – Developers

Coverage Topic

  • Underscore(_) or not underscore with the private member variable
  • Shouldn’t use of var everywhere
  • When must use ‘var
  • When can’t be used  ‘var

Let’s Drill Down the Basic Concept

The Problem

Adam Rusch is my colleague and he is working as “Dot-Net C# developer” in a company. Code-review is the part of his job responsibility. So, during code review, he is confused about the coding standard for the private member variables as well as the use of “var” everywhere as a data-type. He is considering C# as a programing languages and .NET as development platform.

Naming Convention for Private Member Variables

Question: Adam asked me, which convention is standard with underscore or without underscore?

Ans: I said, it depended on the personal preference of the developer. But Adam was not satisfied with the answer.

Investigation to Underscore or not to Underscore

Few programing languages is not case sensitive for example say, Visual Basic (old version). So, in the vb, there is no difference between Pascale case (i.e, VariableName) and camel case (i.e, variableName). Therefore, they use underscore with the private member variable (i.e, _variableName).

The C# is a case sensitive programing language and it knows the difference between pascale case (VariableName) and camel case (variableName).

Therefore,

  • If the C# is a case sensitive programing language, then why am I using underscore (_) prefix before private member variable?
  • What is the extra benefit to use the undescore(_) prefix before private member variable?
  • Am I just only a doer? Few peoples are following this convention and that’s why am I using the same convention?
  • Is it the beauty of readability?  

Solution: First, be a THINKER, then DOER.

Improper Use of ‘Var’ Everywhere

Have a Question

  • In the above example, are these the beauty of readability?  
  • Why am I using var for simple declaration?
  • Why, I can’t say that, these kind of improper use, are an anti-pattern?

Investigation to var or not to var

‘var’ should not be used in simple declarations, shown as bellow –  

When Must Use ‘var’

  • Should be used in LINQ
  • Should be used with anonymous types.

When can’t it be used

There is a restriction, declaring local variables within the method or property, including iteration variable in ‘for’ or ‘foreach’ statements.

  • As a type of field
  • As a type of parameter
  • As a return type of method or property
  • As a type parameter in generic type or method

Solution: First, be a thinker, then doer.

LEAVE A REPLY