Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
We’ve seen that when you declare a variable or constant, you have to tell the compiler what kind of thing it is: Elephant, Goldfish, or Int32. There is an exception to this. Instead of specifying the type, you can use the keyword var to get the compiler to work out the type from the value you provide.
var GuessWhat = "This is a string";
var SomeNumber = 0;
The var keyword is syntactic sugar. The compiler decides what type of thing the variable is. It’s convenient; there are some things that would be tedious to do without it, but you shouldn’t use it unless there’s a good reason to. To find out why, let’s try a little experiment.
1 Create a new WPF Solution and add a button to the Window with the text “Try Me”.
2 Double-click the button and add the following lines to the procedure: