Nominal Vs Structural Type System

Anonymous Types and Tuples might look very similar, but there is one significant difference which separates them. As always, nothing can be more explanatory than writing code.
var anonymous1 = new { x = 1, y = 1 };
var anonymous2 = new { y = 1, x = 1 };

var tuple1 = (x : 1, y : 1);
var tuple2 = (y: 1, x: 1);

Console.WriteLine($"Anonymous Type :  {anonymous1.Equals(anonymous2)}");
Console.WriteLine($"Tuple Type : {tuple1.Equals(tuple2)}");
Consider the above code. What could be the output ? Are both false or are both true ? Interestingly, the output is as follows.
Anonymous Type : False
Tuple Type : True
Though syntactically similar, both Anonymous Types and Tuples vary in a significant factor – the associated type system.  While Anonymous Types is based on Nominal Type System, Tuple is based on Structural Type System. This results in the behavior seen in the above code, with both tuples being equal despite the obvious naming pattern difference.
That brings us to another scenario, what if the sub types for tuples are differently named. For example, consider following code.
var tuple1 = (x : 1, y : 1);
var tuple3 = (a: 1, b: 1);
Console.WriteLine($"Tuple Type : {tuple1.Equals(tuple3)}");
As you would have rightly guessed, the output would be “true” as the tuple is only interested in the types and not the names.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s