What does the keyword var do in C#?


The "var" keyword initializes variables with var support. Just assign whatever value you want for the variable, integer, string, float, etc.

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         var myInt = 5;
         var myString = "Amit";
         Console.WriteLine("Rank: {0} 
Name: {1}",myInt,myString);       }    } }

Output

Rank: 5
Name: Amit

We can also use var in arrays −

Example

 Live Demo

using System;

namespace Demo {
   class Program {
      static void Main(string[] args) {
         var myInt = new int[] {65,43,88,56};
         foreach(var val in myInt)
         Console.WriteLine(val);
      }
   }
}

Output

65
43
88
56

Updated on: 20-Jun-2020

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements