Home  • Programming • C#.NET

Anonymous Types in C#

csharp-dot-net Anonymous type:
  var v = new { Amount = 108, Message = "Hello" };
 Console.WriteLine(v.Amount + v.Message);
Array of anonymous type:
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};
Nested anonymous type:
var student = new { 
                    Id = 1, 
                    FirstName = "James", 
                    LastName = "Bond",
                    Address = new { Id = 1, City = "London", Country = "UK" }
                };
Anonymous type in LINQ:
var productQuery =
    from prod in products
    select new { prod.Color, prod.Price };

foreach (var v in productQuery)
{
    Console.WriteLine("Color={0}, Price={1}", v.Color, v.Price);
}
Use of anonymous type in partial view or component
 @await Component.InvokeAsync("info", new { Color= "Red", Price=30 });

<partial name="_info" model='new {Color="red",Price:"30"}' />
Shared/_info.cshtml or Component View
@model dynamic;

<div>Color:  @Model.Color</div>
@model dynamic;
<div>Price:  @Model.Price</div>

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd