C# Coding Style – Using ‘var’ and Null Coalescing Operator ‘??’ Without Hampering Readability

ccoding-stylereadability

I know the title of the question is very subjective, but I was confronted with usage of ?? operator by my peers, where at the same time I was not very happy/comfortable with applying var in new up-coming code.

The argument given for using ?? operator was, it takes away readability in code.

My question is, doesn't the same thing happens when you start using var?

Best Answer

Null coalescing operator (??)

Personally, I don't see any downsides to using this operator. Consider the following three code samples, from 'easy' to 'complex' new operators.

Without magic:

bool isNameSet = false;
string name;
if ( isNameSet )
{
    Console.WriteLine( name );
}
else
{
    Console.WriteLine( "No name set." );
}

Ternary operator:

bool isNameSet = false;
string name;
Console.WriteLine( isNameSet ? name : "No name set." );

Null coalescing:

string name = null;
Console.WriteLine( name ?? "No name set." );

The reason these operators were invented is because they represent very common programming operations. Not wanting to use them because you aren't used to them is just being stubborn. Languages evolve, features evolve, learn to use them!

var keyword

I have a somewhat different opinion about the var keyword. The type of a variable often gives extra information about your code. I find hiding the type by using the var keyword sometimes makes code less readable. You know less what to expect without using auto completion, or hovering over the identifiers to see what they actually are. In my opinion, this results in code which is slower to read/write.

I do use the keyword when I find that the type doesn't give much extra information.

  • Mainly in foreach loops, which I learned from Resharper as it is a setting there. Most of the time, you know what type of collection you are traversing, so you know you are expecting items from within that collection.
  • Linq queries. The result of linq queries are often very complex generic types. Displaying this type does more harm than good.
  • Long typenames which are simply initialized with their constructor. You can already tell what the type is by looking at the constructor.

As an example for the last statement:

ThisIsSomeSpecializedTypeRightHere duplication =
    new ThisIsSomeSpecializedTypeRightHere();
var justAsReadable =
    new ThisIsSomeSpecializedTypeRightHere();  // Less duplication.

// But I still prefer the following ...
int number = 9;
SomeCreatedType foo = Factory.CreateSomeType();
Related Topic