I’m trying to create a record type in C# with some fields as fixed length strings.
I just want to use this record for further reading of a predefined file format.
I tried this:
public record Person (int age, fixed char birthdate[8]);
However, I’m getting the following error
Array size cannot be specified in a variable declaration (try initializing with a ‘new’ expression)CS0270
I’m using the Visual Studio Code Version: 1.88.1 (Universal).
Can you help me?
Thanks in advance,
Mario
2
Answers
First of all, the best path to folllow is use of Datetime as the comments said, but if you can’t, you could throw an Exception on the record constructor:
With this, the first example will pass, but the second will throw the exception
Fixed-length buffers can be defined as fields on an
unsafe struct
s. This approach can help reduce the need for garbage collection when memory is sparse.But they cannot be used as fields on
record
types (not evenrecord struct
), and they cannot be used as parameters to methods or constructors, as you appear to be trying to do. You would need to take another type (astring
or aSpan<char>
or maybe achar*
) as an argument, and perform any length validation at run-time.But I should point out that this is (as the keyword says)
unsafe
, and the vast majority of C# developers don’t need to get this low-level. Most people are fine using things likestring
s andDateTime
s.