Les Reférences Locales
Avec le nouveau framework, il est possible de modifier directement le champ d’une Struct sans passer par une copie de celle-ci.
Exemple
Point est notre Struct composé de 3 champs entiers X,Y, et Z.
struct Point { public int X; public int Y; public int Z; public override string ToString() { return $"({X}, {Y}, {Z})"; } }
Exemple avec un tableau de Points
Dans l’ancienne version du framework, si on voulait modifier un des Points du tableau il fallait :
Soit pointer sur l’élément à modifier, et modifier les champs de cet éléments (en loccurence les champs de la struct Point)
static void TestArrayStruct() { Point[] myArrayOfPoints = new[] { new Point(), new Point(), new Point() }; myArrayOfPoints[1].X = 1; myArrayOfPoints[1].Y = 1; myArrayOfPoints[1].Z = 1; Console.WriteLine(string.Join(",", myArrayOfPoints)); }
Soit créer un nouvel élement (Point dans notre cas), lui assigner l’élement du tableau à modifier, modifier les champs de ce nouvel élément, copier le nouveau Point à l’élément à modifier…bref c’est assez lourd…
static void TestArrayStructLocalVar() { Point[] myArrayOfPoints = new[] { new Point(), new Point(), new Point() }; Point p = myArrayOfPoints[1]; p.X = 1; p.Y = 1; p.Z = 1; myArrayOfPoints[1] = p; //copy p to myArrayOfPoints Console.WriteLine(string.Join(",", myArrayOfPoints)); }
Aujourd’hui en applicant le mot clé ref à notre nouveau point ET à l’élément du tableau à modifier, on peut modifier directement le nouveau Point sans faire de recopie.
static void TestRefLocal() { Point[] a = new[] { new Point(), new Point(), new Point() }; ref Point p = ref a[1]; //enable Struct member to be modified //without doing any copy p.X = 1; p.Y = 1; p.Z = 1; Console.WriteLine(string.Join(",", a)); }
Sortie
(0, 0, 0),(1, 1, 1),(0, 0, 0)