Skip to content

Commit 22cfc48

Browse files
committed
move code samples to snippets
1 parent fd0cceb commit 22cfc48

File tree

2 files changed

+118
-78
lines changed

2 files changed

+118
-78
lines changed

docs/csharp/fundamentals/types/anonymous-types.md

Lines changed: 7 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -45,68 +45,19 @@ The following example shows how tuples provide similar functionality to anonymou
4545

4646
You can deconstruct a tuple into separate variables, which provides a convenient way to work with individual tuple elements. C# supports several ways to deconstruct tuples:
4747

48-
```csharp
49-
// Define a method that returns a tuple
50-
(string Name, int Age, string City) GetPersonInfo()
51-
{
52-
return ("Alice", 30, "Seattle");
53-
}
54-
55-
// Deconstruct using var for all variables
56-
var (name, age, city) = GetPersonInfo();
57-
Console.WriteLine($"{name} is {age} years old and lives in {city}");
58-
// Output: Alice is 30 years old and lives in Seattle
59-
60-
// Deconstruct with explicit types
61-
(string personName, int personAge, string personCity) = GetPersonInfo();
62-
Console.WriteLine($"{personName}, {personAge}, {personCity}");
63-
64-
// Deconstruct into existing variables
65-
string existingName;
66-
int existingAge;
67-
string existingCity;
68-
(existingName, existingAge, existingCity) = GetPersonInfo();
69-
70-
// Deconstruct and discard unwanted values using the discard pattern (_)
71-
var (name2, _, city2) = GetPersonInfo();
72-
Console.WriteLine($"{name2} lives in {city2}");
73-
// Output: Alice lives in Seattle
74-
```
48+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="TupleDeconstructionMethod":::
7549

76-
Deconstruction is useful in loops and pattern matching scenarios:
50+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="TupleDeconstruction":::
7751

78-
```csharp
79-
var people = new List<(string Name, int Age)>
80-
{
81-
("Bob", 25),
82-
("Carol", 35),
83-
("Dave", 40)
84-
};
52+
Deconstruction is useful in loops and pattern matching scenarios:
8553

86-
foreach (var (name, age) in people)
87-
{
88-
Console.WriteLine($"{name} is {age} years old");
89-
}
90-
```
54+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="TupleDeconstructionLoop":::
9155

9256
### Tuples as a method return type
9357

9458
A common use case for tuples is as a method return type. Instead of defining `out` parameters, you can group method results in a tuple. The following example demonstrates using tuples with dictionary lookups to return configuration ranges:
9559

96-
```csharp
97-
var configLookup = new Dictionary<int, (int Min, int Max)>()
98-
{
99-
[2] = (4, 10),
100-
[4] = (10, 20),
101-
[6] = (0, 23)
102-
};
103-
104-
if (configLookup.TryGetValue(4, out (int Min, int Max) range))
105-
{
106-
Console.WriteLine($"Found range: min is {range.Min}, max is {range.Max}");
107-
}
108-
// Output: Found range: min is 10, max is 20
109-
```
60+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="DictionaryTupleExample":::
11061

11162
This pattern is useful when working with methods that need to return both a success indicator and multiple result values. The tuple allows you to use named fields (`Min` and `Max`) instead of generic names like `Item1` and `Item2`, making the code more readable and self-documenting.
11263

@@ -158,9 +109,7 @@ Typically, when you use an anonymous type to initialize a variable, you declare
158109

159110
You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example.
160111

161-
```csharp
162-
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};
163-
```
112+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="AnonymousArray":::
164113

165114
Anonymous types are [`class`](../../language-reference/keywords/class.md) types that derive directly from [`object`](../../language-reference/builtin-types/reference-types.md), and you can't cast them to any type except [`object`](../../language-reference/builtin-types/reference-types.md). The compiler provides a name for each anonymous type, although your application can't access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
166115

@@ -180,11 +129,7 @@ Because the <xref:System.Object.Equals%2A> and <xref:System.Object.GetHashCode%2
180129
181130
Anonymous types do override the <xref:System.Object.ToString%2A> method, concatenating the name and `ToString` output of every property surrounded by curly braces.
182131

183-
```
184-
var v = new { Title = "Hello", Age = 24 };
185-
186-
Console.WriteLine(v.ToString()); // "{ Title = Hello, Age = 24 }"
187-
```
132+
:::code language="csharp" source="snippets/anonymous-types/Program.cs" ID="ToStringExample":::
188133

189134
## See also
190135

docs/csharp/fundamentals/types/snippets/anonymous-types/Program.cs

Lines changed: 111 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,106 @@ namespace anonymous_types
77
// <ProductDefinition>
88
class Product
99
{
10-
public string? Color { get; set; }
11-
public decimal Price { get; set; }
12-
public string? Name { get; set; }
13-
public string? Category { get; set; }
14-
public string? Size { get; set; }
10+
public string? Color { get; init; }
11+
public decimal Price { get; init; }
12+
public string? Name { get; init; }
13+
public string? Category { get; init; }
14+
public string? Size { get; init; }
1515
}
1616
// </ProductDefinition>
17+
1718
class Anonymous
1819
{
20+
// <TupleDeconstructionMethod>
21+
static (string Name, int Age, string City) GetPersonInfo()
22+
{
23+
return ("Alice", 30, "Seattle");
24+
}
25+
// </TupleDeconstructionMethod>
26+
1927
static void Main()
2028
{
21-
// Don't show this unless you add a bunch more
22-
// properties to the type. Otherwise it obviates the
23-
// need for the anonymous type.
29+
TupleExamples();
30+
TupleDeconstructionExamples();
31+
TupleMethodReturnExample();
32+
AnonymousTypeExamples();
33+
ProjectionInitializerExamples();
34+
AnonymousArrayExample();
35+
ToStringExample();
36+
}
37+
38+
static void TupleExamples()
39+
{
40+
// <TupleExample>
41+
// Anonymous type example.
42+
var anonymousProduct = new { Name = "Widget", Price = 19.99M };
43+
Console.WriteLine($"Anonymous: {anonymousProduct.Name} costs ${anonymousProduct.Price}");
44+
45+
// Equivalent using a tuple with named elements.
46+
var tupleProduct = (Name: "Widget", Price: 19.99M);
47+
Console.WriteLine($"Tuple: {tupleProduct.Name} costs ${tupleProduct.Price}");
48+
// </TupleExample>
49+
}
50+
51+
static void TupleDeconstructionExamples()
52+
{
53+
// <TupleDeconstruction>
54+
// Deconstruct using var for all variables
55+
var (name, age, city) = GetPersonInfo();
56+
Console.WriteLine($"{name} is {age} years old and lives in {city}");
57+
// Output: Alice is 30 years old and lives in Seattle
58+
59+
// Deconstruct with explicit types
60+
(string personName, int personAge, string personCity) = GetPersonInfo();
61+
Console.WriteLine($"{personName}, {personAge}, {personCity}");
62+
63+
// Deconstruct into existing variables
64+
string existingName;
65+
int existingAge;
66+
string existingCity;
67+
(existingName, existingAge, existingCity) = GetPersonInfo();
68+
69+
// Deconstruct and discard unwanted values using the discard pattern (_)
70+
var (name2, _, city2) = GetPersonInfo();
71+
Console.WriteLine($"{name2} lives in {city2}");
72+
// Output: Alice lives in Seattle
73+
// </TupleDeconstruction>
74+
75+
// <TupleDeconstructionLoop>
76+
var people = new List<(string Name, int Age)>
77+
[
78+
("Bob", 25),
79+
("Carol", 35),
80+
("Dave", 40)
81+
];
82+
83+
foreach (var (name, age) in people)
84+
{
85+
Console.WriteLine($"{name} is {age} years old");
86+
}
87+
// </TupleDeconstructionLoop>
88+
}
89+
90+
static void TupleMethodReturnExample()
91+
{
92+
// <DictionaryTupleExample>
93+
var configLookup = new Dictionary<int, (int Min, int Max)>()
94+
{
95+
[2] = (4, 10),
96+
[4] = (10, 20),
97+
[6] = (0, 23)
98+
};
99+
100+
if (configLookup.TryGetValue(4, out (int Min, int Max) range))
101+
{
102+
Console.WriteLine($"Found range: min is {range.Min}, max is {range.Max}");
103+
}
104+
// Output: Found range: min is 10, max is 20
105+
// </DictionaryTupleExample>
106+
}
107+
108+
static void AnonymousTypeExamples()
109+
{
24110
List<Product> products =
25111
[
26112
new Product { Color = "Orange", Price = 2.00M }
@@ -50,7 +136,10 @@ from prod in products
50136
var shipment = new { address = "Nowhere St.", product };
51137
var shipmentWithBonus = new { address = "Somewhere St.", product, bonus };
52138
// </Snippet03>
139+
}
53140

141+
static void ProjectionInitializerExamples()
142+
{
54143
// <ProjectionInitializers>
55144
// Explicit member names.
56145
var personExplicit = new { FirstName = "Kyle", LastName = "Mit" };
@@ -78,16 +167,22 @@ from prod in products
78167

79168
Console.WriteLine($"Title: {employee.title}, Department: {employee.department}, Salary: {employee.salary}");
80169
// </ProjectionExample>
170+
}
81171

82-
// <TupleExample>
83-
// Anonymous type example.
84-
var anonymousProduct = new { Name = "Widget", Price = 19.99M };
85-
Console.WriteLine($"Anonymous: {anonymousProduct.Name} costs ${anonymousProduct.Price}");
172+
static void AnonymousArrayExample()
173+
{
174+
// <AnonymousArray>
175+
var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }};
176+
// </AnonymousArray>
177+
}
86178

87-
// Equivalent using a tuple with named elements.
88-
var tupleProduct = (Name: "Widget", Price: 19.99M);
89-
Console.WriteLine($"Tuple: {tupleProduct.Name} costs ${tupleProduct.Price}");
90-
// </TupleExample>
179+
static void ToStringExample()
180+
{
181+
// <ToStringExample>
182+
var v = new { Title = "Hello", Age = 24 };
183+
184+
Console.WriteLine(v.ToString()); // "{ Title = Hello, Age = 24 }"
185+
// </ToStringExample>
91186
}
92187
}
93188
}

0 commit comments

Comments
 (0)