Today’s tip is specific to C#.
OK, let’s get into it.
In C#, we may declare and assign a local integer variable,
customNumber, like this:
int customerNumber = Customer.CustomerNumber;
However, we’ve been asked to change the system to allow non-integer customer numbers like ‘C123456X’ and ‘BOB-SMITH76’. To complete our task, we would change customer numbers from
What will happen to all those instances where we had declared integer references to hold customer numbers, like the above example?
Say, we had 57 such references throughout our system. We will have at least 57 compilation errors! That’s a lot of errors. To fix these, we go ahead and change the declarations to be of type
string customerNumber = Customer.CustomerNumber;
Making 57 modifications to our system is risky. There’s always the chance that we make a mistake. Besides, what if the customer number’s data type changes again? Do we have to go through the same tedious process again?
No—we don’t need to repeat the pain if we only declare our references as
var customerNumber = Customer.CustomerNumber;
Here we have an implicit local variable declaration. Such a declaration will succeed as long as there is an assignment from which the compiler can infer the declared data type. For example, the compiler knows the data type of
Customer.CustomerNumber. Under the hood, it will set local reference
customerNumber to be of the same type. That process will work whether
Customer.CustomerNumber is an
string or another data type.
The compiler must be able to determine the data type of the implicit declaration. We can’t do this:
There are no hints as to the type index should be.
var index = 0;
will work—the initialisation to zero hints at the index being an
var we are more aligned with the SOLID Principles’ Open-Closed Principle, which states “software entities should be open for extension, but closed for modification.”
Choosing a specific data type for our declaration of
customerNumber may require a modification to 57 locations in our code. On the other hand,
var handles a data type change for customer number with no changes to local variable declarations.
customerNumber means we do not need to change the declaration when the underlying data type for the assigned value changes. We have made our program more robust to data type changes.
var is not just syntactic sugar. It has a real impact on software maintainability.
In C#, prefer var.