Skip to content

Instantly share code, notes, and snippets.

@20chan
Created September 14, 2017 05:36
Show Gist options
  • Select an option

  • Save 20chan/d75ce38297000a641acd635b16795a11 to your computer and use it in GitHub Desktop.

Select an option

Save 20chan/d75ce38297000a641acd635b16795a11 to your computer and use it in GitHub Desktop.
C# list of structures reference testing
using System;
using System.Collections.Generic;
namespace struct_reference
{
class Program
{
static void Main(string[] args)
{
Point p1 = new Point(10, 10);
Point p2 = new Point(20, 20);
Point p3 = new Point(30, 30);
var list = new List<Point> { p1, p2, p3 }; // Members of list is not referencal equal to p1, p2, p3
// list[0].X = 100; Compile err
var ppap = list[0]; // ppap is new instance of point, just copied values of p1.
ppap.X = 100;
Console.WriteLine(p1); // => (10, 10), Not changed
list[0].SetX(100);
Console.WriteLine(p1);
Console.Read(); // => (10, 10), Still not changed
}
}
struct Point
{
public int X, Y;
public Point(int x, int y)
{
X = x; Y = y;
}
public override string ToString() => $"({X}, {Y})";
public void SetX(int new_x) => X = new_x;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment