-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProgram.cs
More file actions
54 lines (47 loc) · 2 KB
/
Program.cs
File metadata and controls
54 lines (47 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
namespace _16AnonymousTypes
{
class Program
{
static void Main(string[] args)
{
//ANONYMOUS TYPES
Console.WriteLine("------------------Anonymous Types------------------");
//Anonymous types are similar to tuples (see project 16Tuples) but are used differently.
//We instantiate an anonymous type using the var keyword.
var myAnonymous = new { Name = "John Smith", Age = 4 };
Console.WriteLine(myAnonymous);
var users = new List<User>()
{
new User()
{
Name = "Test User 1",
Age = 30,
DateOfBirth = new DateTime(1990, 5, 21)
},
new User()
{
Name = "Test User 2",
Age = 55,
DateOfBirth = new DateTime(1965, 3, 10)
}
};
//The most common scenario for anonymous types is in LINQ queries.
//Specifically, LINQ projections:
var results = users.Where(x => x.Age > 40)
.Select(x => new { x.Name, x.Age }); //Anonymous type
foreach (var item in results)
{
Console.WriteLine("Name: " + item.Name + ", Age: " + item.Age);
}
//Anonymous types are immutable (their properties cannot be modified once created)
//and they are not types in the traditional sense. Their type is generated
//by the compiler. Consequently they come with some restrictions
//1. Anonymous types cannot be used as parameters or return values (see 6Methods).
//2. Anonymous types may only have properties; constructors or other methods are not permitted.
//3. Anonymous types inherit from System.Object, and therefore cannot be cast to any other object.
}
}
}