|
| 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