Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 525
Paul Spencer Avatar asked May 13 '14 08:05

Paul Spencer


2 Answers

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)
like image 79
Patrick Hofman Avatar answered Oct 23 '22 15:10

Patrick Hofman


One very important reason is that it helps to prevent errors caused by accidentally mistyping a variable name.

Imagine, you want to reassign string myString to have a new value:

myString = "New value";

But you accidentally type this:

myStrimg = "New value";

This will cause a compile-time error. However, if you allow implicitly created variables per your question, this will silently create a new variable, with predictably hilarious results...

like image 39
Matthew Watson Avatar answered Oct 23 '22 16:10

Matthew Watson