« Parameter modifiers » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 29 : Ligne 29 :
Useful when you have a big value type and you want to pass only its reference for performances reason, but you don't want it to be overwritten.
Useful when you have a big value type and you want to pass only its reference for performances reason, but you don't want it to be overwritten.
<kode lang='cs'>
<kode lang='cs'>
var item = new Item("name");
var bigStruct = new BigStruct("name");
Method(ref item);
Method(ref bigStruct);


void Method(ref readonly Item item)
void Method(ref readonly BigStruct bigStruct)
{
{
     item = new Item("new name"); // you can't assign a readonly variable
     bigStruct = new BigStruct("new name"); // you can't assign a readonly variable
     item.Name = "new name";     // you can modify the object properties
     bigStruct.Name = "new name";           // you can modify the object properties
}
}
</kode>
</kode>

Version du 24 mai 2024 à 15:24

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 (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");

ref readonly

Pass a parameter by reference and make it readonly.
Useful when you have a big value type and you want to pass only its reference for performances reason, but you don't want it to be overwritten.

Cs.svg
var bigStruct = new BigStruct("name");
Method(ref bigStruct);

void Method(ref readonly BigStruct bigStruct)
{
    bigStruct = new BigStruct("new name"); // you can't assign a readonly variable
    bigStruct.Name = "new name";           // you can modify the object properties
}

out

Allow to initialize the parameter in the method.

Cs.svg
Method5(out var j); // 5

void Method5(out int i) => i = 5;