Skip to content

Commit 4dbaf69

Browse files
authored
Update samples for readonly (#133)
Move existing snippets from docs repo. Add samples for new uses of readonly.
1 parent 925abc6 commit 4dbaf69

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

snippets/csharp/keywords/Program.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ static void Main(string[] args)
1414
FixedKeywordExamples.Examples();
1515
Console.WriteLine("================= Iteration Keywords Examples ======================");
1616
IterationKeywordsExamples.Examples();
17+
Console.WriteLine("================= readonly Keyword Examples ======================");
18+
ReadonlyKeywordExamples.Examples();
1719
}
1820
}
1921
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace keywords
6+
{
7+
// <SnippetReadonlyField
8+
class Age
9+
{
10+
readonly int year;
11+
Age(int year)
12+
{
13+
this.year = year;
14+
}
15+
void ChangeYear()
16+
{
17+
//year = 1967; // Compile error if uncommented.
18+
}
19+
}
20+
// </SnippetReadonlyField>
21+
22+
// <SnippetInitReadonlyField>
23+
class SampleClass
24+
{
25+
public int x;
26+
// Initialize a readonly field
27+
public readonly int y = 25;
28+
public readonly int z;
29+
30+
public SampleClass()
31+
{
32+
// Initialize a readonly instance field
33+
z = 24;
34+
}
35+
36+
public SampleClass(int p1, int p2, int p3)
37+
{
38+
x = p1;
39+
y = p2;
40+
z = p3;
41+
}
42+
43+
public static void Usage()
44+
{
45+
SampleClass p1 = new SampleClass(11, 21, 32); // OK
46+
Console.WriteLine($"p1: x={p1.x}, y={p1.y}, z={p1.z}");
47+
SampleClass p2 = new SampleClass();
48+
p2.x = 55; // OK
49+
Console.WriteLine($"p2: x={p2.x}, y={p2.y}, z={p2.z}");
50+
}
51+
/*
52+
Output:
53+
p1: x=11, y=21, z=32
54+
p2: x=55, y=25, z=24
55+
*/
56+
}
57+
// </SnippetInitReadonlyField>
58+
59+
// <SnippetReadonlyStruct>
60+
public readonly struct Point
61+
{
62+
public double X { get; }
63+
public double Y { get; }
64+
65+
public Point(double x, double y) => (X, Y) = (x, y);
66+
67+
public override string ToString() => $"({X}, {Y})";
68+
}
69+
// </SnippetReadonlyStruct>
70+
71+
public static class ReadonlyKeywordExamples
72+
{
73+
public static void Examples()
74+
{
75+
SampleClass.Usage();
76+
ReadonlyRefReturns();
77+
}
78+
79+
// <SnippetReadonlyReturn>
80+
private static readonly Point origin = new Point(0, 0);
81+
public static ref readonly Point Origin => ref origin;
82+
// </SnippetReaodnlyReturn>
83+
84+
private static void ReadonlyRefReturns()
85+
{
86+
Console.WriteLine(Origin);
87+
}
88+
}
89+
}

0 commit comments

Comments
 (0)