« Parameter modifiers » : différence entre les versions
Apparence
Aucun résumé des modifications |
|||
Ligne 23 : | Ligne 23 : | ||
// if the parameter is overwritten (the initial reference is overwritten), it does affect the initial object | // if the parameter is overwritten (the initial reference is overwritten), it does affect the initial object | ||
void Method3(ref Item item) => item = new("new name 3"); | void Method3(ref Item item) => item = new("new name 3"); | ||
</kode> | |||
= [https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/method-parameters#out-parameter-modifier out] = | |||
Allow to initialize the parameter in the method. | |||
<kode lang='cs'> | |||
Method5(out var j); // 5 | |||
void Method5(out int i) => i = 5; | |||
</kode> | </kode> |
Version du 24 mai 2024 à 15:15
ref
Pass a parameter by reference.
// value type
var i = 10;
Method0(i); // 10
Method1(ref i); // 11
void Method0(int i) => i++; // pass the value type parameter by value (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 passed by value (copy)
// if the parameter is overwritten (the copy of the reference is overwritten), 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 by reference
// if the parameter is overwritten (the initial reference is overwritten), it does affect the initial object
void Method3(ref Item item) => item = new("new name 3");
|
out
Allow to initialize the parameter in the method.
Method5(out var j); // 5
void Method5(out int i) => i = 5;
|