I do stuff where having contiguous data is required. Now with C# 10, we can do public readonly record struct.
I like having the automatic ToString feature that records have, among others, so having that done for me is nice.
As such, are the following equivalent?
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public readonly struct MyVector
{
public readonly float X;
public readonly float Y;
public readonly float Z;
public MyVector(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
}
versus the nicely condensed C# 10 version
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public readonly record struct MyVectorRecord(float X, float Y, float Z)
{
}
Or are there any landmines I'm going to accidentally step on doing this? By which I mean are there any things being done under the hood by record that make what I've written above not do what I want with respect to contiguous packing? I can't have the record insert padding, spacing, or do anything weird.
I am not using a vector class with record structs and was using this for purposes of illustration. You can ignore things like "floating point equality comparisons" since I am only interested in whether I can pass this off to a library that is expecting a contiguous sequence of X/Y/Z's.
recordisn't a new type, it's specific behavior applied to reference and now value types. The struct remains a struct. You can test this at sharplab.io, to see the code generated by the compiler in each case.A record uses properties though, not raw fields, so you can only compare structs with properties to record structs. That's the important difference
This struct:
produces
While the record
produces:
Finally, this
Remains unchanged, apart from the
IsReadOnlyattribute.The big difference is between structs with fields and structs with public properties. After that, a
record structcontains only extra methods compared to a struct with properties.