Skip to content

Commit b30aef3

Browse files
CopilotBillWagner
andauthored
Improve in parameter modifier example with meaningful struct-based demonstration (#47134)
* Initial plan * Improve in parameter modifier example with more meaningful struct-based demonstration Co-authored-by: BillWagner <[email protected]> --------- Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: BillWagner <[email protected]>
1 parent 0e3e811 commit b30aef3

File tree

1 file changed

+33
-6
lines changed

1 file changed

+33
-6
lines changed

docs/csharp/language-reference/keywords/snippets/RefParameterModifier.cs

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,32 @@ private static void OutVariableDeclaration()
8686
private static void FirstInExample()
8787
{
8888
// <InParameterModifier>
89-
int readonlyArgument = 44;
90-
InArgExample(readonlyArgument);
91-
Console.WriteLine(readonlyArgument); // value is still 44
92-
93-
void InArgExample(in int number)
89+
var largeStruct = new LargeStruct { Value1 = 42, Value2 = 3.14, Value3 = "Hello" };
90+
91+
// Using 'in' avoids copying the large struct and prevents modification
92+
ProcessLargeStruct(in largeStruct);
93+
Console.WriteLine($"Original value unchanged: {largeStruct.Value1}");
94+
95+
// Without 'in', the struct would be copied (less efficient for large structs)
96+
ProcessLargeStructByValue(largeStruct);
97+
Console.WriteLine($"Original value still unchanged: {largeStruct.Value1}");
98+
99+
void ProcessLargeStruct(in LargeStruct data)
94100
{
101+
// Can read the values
102+
Console.WriteLine($"Processing: {data.Value1}, {data.Value2}, {data.Value3}");
103+
95104
// Uncomment the following line to see error CS8331
96-
//number = 19;
105+
// data.Value1 = 99; // Compilation error: cannot assign to 'in' parameter
106+
}
107+
108+
void ProcessLargeStructByValue(LargeStruct data)
109+
{
110+
// This method receives a copy of the struct
111+
Console.WriteLine($"Processing copy: {data.Value1}, {data.Value2}, {data.Value3}");
112+
113+
// Modifying the copy doesn't affect the original
114+
data.Value1 = 99;
97115
}
98116
// </InParameterModifier>
99117
}
@@ -111,6 +129,15 @@ public struct OptionStruct
111129
{
112130
// taking the place of lots of fields
113131
}
132+
133+
public struct LargeStruct
134+
{
135+
public int Value1;
136+
public double Value2;
137+
public string Value3;
138+
// In a real scenario, this struct might have many more fields
139+
// making copying expensive
140+
}
114141
// <Snippet4>
115142

116143
public class Book

0 commit comments

Comments
 (0)