Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

var
c #

What is the "var" keyword in C#?

Educative Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The “var” keyword shifts the responsibility of selecting the data type of a variable from the programmer to the compiler. How?

  • If the “var” keyword is used before the name of a variable, its type need not be defined.
  • When the code is run, the compiler decides the data type for the variable itself.

A “var” type variable cannot be null. It must always have a value. Think of it this way- you can’t keep a hidden object on the desk and guess what it is. The same way, you can’t have a null variable and expect the compiler to decide its data type.

Usually, the “var” keyword is used when the data type of the variable is exceptionally long and it’s tedious to keep repeating it. Moreover, in array lists when there are elements of multiple data types, it’s efficient to declare the type as “var” and let the compiler decide the type of each element.

using System;
class varKeyword
{
    static void Main()
    {
      var i=5;
      var j=10;
      Console.WriteLine(i+j);
   }
}
The two "var" variables are compiled as ints and their summation is shown in the final step

RELATED TAGS

var
c #
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring