var in x++ Programming Language

Rumman Ansari   Software Engineer   2023-08-23 00:00:00   542  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

var in x++ Programming Language

You can declare a variable without explicitly providing the type of the variable, if the compiler can determine the type from the initialization expression. The variable is still strongly-typed into one, unambiguous type.

You can use var only on declarations where initialization expressions are provided. (The compiler will infer the type from the initialization expression.) In some cases, this approach can make code easier to read.

You should use var to declare local variables in these situations:

  • When the type of the variable is obvious from the right side of the assignment
  • When the exact type isn't important
  • For the declarations of for loop counters
  • For disposable objects inside using statements

Don't use var when the type isn't clear from the initialization expression.


var examples


// When the type of a variable is clear from
// the context, use var in the declaration.
var var1 = "This is clearly a string.";
var var2 = 27; // This is an integer (not a real).
var i = System.Convert::ToInt32(3.4);

// Don't use var when the type of the variable is not clear
// from the context. Use an explicit type instead.
int var4 = myObject.ResultSoFar();