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
Of course, that would be possible.
I can think of a few reasons you don't want this:
animals
in two methods become a private variable or two method scoped variables?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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With