C# language feature:

  • Implicitly typed local variables

applies to

  • anonymous types, local variable declarations

benefit

  • Allows a placeholder for anonymous types, which are often used in query expressions. Additionally, allows simplified declaration of local variables.

how to use

  • Use the var contextual keyword (instead of a type specifier).

note

  • Use of var does not hinder type safety. It allows convienient delaration of variables.

example:

        void Use_of_Implicit_Types_Example()
        {
            var x = 5;  // variable x is an int
            var mystring = "test"; // variable mystring is a string

            List<int> ratings = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var highratings = from rating in ratings
                              where rating > 7
                              select new { highrating = rating };  // `var` used here to declare and assign a new anonymous type
        }