The keyword “var” and Anonymous Object in C# programming
The keyword var is a way to declare a variable without specifying its data type. The C# compiler will automatically infer the data type of the variable based on the value assigned to it. For example:
// x is int type
var x = 99;
// y is string type
var y = "Hi";
// z is anonymous type
var z = new {
Name = "Thinh"
};
Anonymous Object is a data type that has no name, created using the Object Initializer syntax. Anonymous Object can only contain data and cannot change its value after being initialized. For example:
// person is an anonymous object
var person = new {
Name = "Kelly",
Age = 21
};
// Kelly
Console.WriteLine(person.Name);
// 21
Console.WriteLine(person.Age);
// Error:
// cannot assign value
// to property
// of anonymous object
person.Age = 31;
The keyword var is often used to declare variables for Anonymous Object, because there is no way to know the name of this data type. However, the keyword var can also be used for other data types, as long as the value assigned to the variable can determine the type.