John Lam 1997 — 2026

CLR Value Types in Ruby

I thought I’d expand a bit on a problem that I solved today. Consider this bit of C# code:

Point p1 = new Point(2, 3);
Point p2 = p1;
p2.X += 1;
Assert.Equals(p1.X + 1, p2.X);

This should run without throwing an assertion, right? That’s because the semantics of value types in the CLR dictate that they must be copied upon assignment.

However, consider this Ruby code that uses my bridge:

p1 = Point.new(2, 3)
p2 = p1
p2.X += 1
assert_equal p1.X, p2.X

This code also runs without throwing an assertion. What you’re seeing is Ruby treating all objects as reference types for assignment purposes. Ruby doesn’t know anything about .NET value types, so its behavior is consistent with its type system.

However, if you use the Ruby clone method, you will see the same behavior as the C# code:

p1 = Point.new(2, 3)
p2 = p1.clone
p2.X += 1
assert_equal p1.X + 1, p2.X

I had to do a bit of hacking to implement clone semantics correctly for T_DATA Ruby C object types. There’s still some work to be done to implement clone correctly for CLR reference types once I turn my attention to object identity in the near future.