Updated on Kisan Patel
Anonymous types defined with var keyword. So A simple anonymous type variable begins with the var
keyword, the assignment operator (=), and a non null initial value.
For Example,
var name = "Kisan";
Here, we have assign name anonymous variable with string value “Kisan” and this is identical to the following.
string name = "Kisan";
Note : Anonymous types must always have an initial assignment and it can’t be null.
Anonymous types mean you don’t specify the data type. You write var
and C# find what data type is defined in right side.
You can also use anonymous type syntax for initializing arrays. You can initialize anonymous type using new
keyword.
For Example,
var names = new string[]{ "Kisan", "Ketul", "Ravi", "Ujas" }; Console.WriteLine(names[1]);
You Can be used anonymous type with Simple or complex types, but composite anonymous types require member declaration. So Anonymous types that define composite types is just class without the “typed” class definition.
For Example,
var name = new {First=”Kisan”, Last=”Patel”}; Console.WriteLine(name.First); //Print the Kisan Console.WriteLine(name.Patel); //Print the Patel
Here, the member elements, defined by the member declarators are First and Last.
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { var names = new { First = "Kisan" , Last = "Patel" }; Console.WriteLine(names.First); Console.WriteLine(names.Last); Console.WriteLine(names); } } }
The output of the above C# program…