« Parameter modifiers » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 1 : Ligne 1 :
[[Category:CSharp]]
[[Category:CSharp]]
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#ref-parameter-modifier ref] =
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#ref-parameter-modifier ref] =
Pass a value parameter by reference.
Pass a parameter by reference.
<kode lang='cs'>
<kode lang='cs'>
// value type
var i = 10;
var i = 10;
Method0(i);    // 10
Method0(i);    // 10
Ligne 9 : Ligne 10 :
void Method0(int i) => i++;    // pass the value type parameter by value: make a copy
void Method0(int i) => i++;    // pass the value type parameter by value: make a copy
void Method1(ref int i) => i++; // pass the value type parameter by reference
void Method1(ref int i) => i++; // pass the value type parameter by reference
// reference type
var item = new Item("init name");
Method2(item);    // init name
Method3(ref item); // new name 3
// pass the reference type parameter by value: the reference is copied and passed to the method
// if the parameter is overwritten by another one, it doesn't affect the initial object
void Method2(Item item) => item = new("new name 2");
// pass the reference type parameter by reference: the reference is passed to the method
// if the parameter is overwritten by another one, it does affect the initial object
void Method3(ref Item item) => item = new("new name 3");
</kode>
</kode>

Version du 24 mai 2024 à 15:02

ref

Pass a parameter by reference.

Cs.svg
// value type
var i = 10;
Method0(i);     // 10
Method1(ref i); // 11

void Method0(int i) => i++;     // pass the value type parameter by value: make a copy
void Method1(ref int i) => i++; // pass the value type parameter by reference

// reference type
var item = new Item("init name");
Method2(item);     // init name
Method3(ref item); // new name 3

// pass the reference type parameter by value: the reference is copied and passed to the method
// if the parameter is overwritten by another one, it doesn't affect the initial object
void Method2(Item item) => item = new("new name 2");

// pass the reference type parameter by reference: the reference is passed to the method
// if the parameter is overwritten by another one, it does affect the initial object
void Method3(ref Item item) => item = new("new name 3");