2

I'm trying to study Dart and I noticed in the online documentation that if the class has custom constructor the example of initializing the class is like this:

Employee emp = new Employee();

Now my question is what is the difference between this code and the previous one?

var emp = new Employee();

I tested both in online sandbox and constructors are both invoked. When do I use which code?

PS I'm not sure if this was already asked since I don't know the term of it in Dart.

threeFatCat
  • 840
  • 13
  • 30
  • 1
    Does this answer your question? [Use of var keyword in C#](https://stackoverflow.com/questions/41479/use-of-var-keyword-in-c-sharp) – Uwe Keim Mar 02 '20 at 04:44
  • Base on the top answer in your link, does it mean **it doesn't have any difference at all**? it is just a plain declarative(noise)? Sorry I don't have background in C#. I have background Javascript. So it's not that much clear to me. Thanks. – threeFatCat Mar 02 '20 at 04:50
  • 1
    At least in C#, it is just a shortcut to avoid writing the type, when the compiler can find it out by itself. I can only assume that for Dart it is similar. See [this answer](https://stackoverflow.com/a/12416873/107625). – Uwe Keim Mar 02 '20 at 04:52

1 Answers1

2

It doesn't make any difference because Dart is inferring the variable type from the value you assign. You would typically mention a class when you don't initialize the variable :

var value; // This is a dynamic variable of null value
int value; // This is an int variable of null value

More on inference and the Dart type system

MickaelHrndz
  • 3,604
  • 1
  • 13
  • 23