Search code examples
c#.netvariablesclrdeclaration

Why are declarations necessary


I am currently teaching a colleague .Net and he asked me a question that stumped me.

Why do we have to declare?

if var is implicit typing, why do we have to even declare?

Animal animal = new Animal();

becomes

var animal = new Animal();

could become

animal = new Animal();

The implicit typing would still mean that this is a statically typed variable.

If two different types are assigned to the variable, if they do not share a base class, (other than object), that could be a compiler error.

Is there a technical reason this could not be done or is it stylistically we like havein


Solution

  • Of course, that would be possible.

    I can think of a few reasons you don't want this:

    1. What is the scope of your variable? Not clear if you don't tell the compiler. Will animals in two methods become a private variable or two method scoped variables?
    2. What if the name is a typo? You will never know.
    3. What if you already assigned a value to this variable and then try to assign a new value which is incompatible with the last (i.e javascript style) (credits to Mario Stoilov)