Var usage in C#Aug 26, 2015 1 minute read
The following code snippets illustrate how the usage of the
var keyword can shorten the feedback loop and prevent errors.
Simple class hierarchy
Code without using
The code will compile successfully. However, at runtime it will blow up pretty bad. There is no way to fit a
Cat into a
The code will not even compile. The compiler infers
arr to be an array of Dogs. It prevents Cats from being inserted into the array.
In both cases the code fails. However, the usage of
var allows some errors to be catched during compilation. Errors are preferably catched as early as possible.
The code from the first snippet could have easily made it into production impacting the application users. Whereas the code from the second snippet was catched by the developer who wrote it. 1