var type in c#


Local variables can be given an inferred "type" of var instead of an explicit type.

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement, So called as Implicitly typed local variables

The inferred type may be a built-in type, an anonymous type, a user-defined type, a type defined in the .NET Framework class library, or any expression.

The var keyword may be used in the following contexts
  • On local variables (variables declared at method scope)
  • In a for initialization statement.
     For(var x=1;x<=10;x++)
  • In a foreach initialization statement.
    Foreach(var x in A)

for all data types in c#.NET, refer Datatypes in c#

Example Program for var in C#



using System;

 

namespace ProgramCall

{

 

    class MainClass

    {

        static void Main(string[] args)

        {

            // The var keyword instructs the compiler to infer the type of

            //the variable from the expression on the right side of the

            //initialization statement.

            var num = 56;

            var num2 = 99.34;

 

            Console.WriteLine(num.GetType());

            Console.WriteLine(num2.GetType());

 

            Console.Read();

        }

    }

}



Output
System.Int32
System.Double



c# var keyword, var keyword c#, var type c#, var type in c#, var keyword in c#, Example Program for var in C#, Implicitly typed local variables