Explicit field layouts should be taken into account when determining whether all fields of a struct have been assigned. #659
Replies: 4 comments
-
Finally! 👍 |
Beta Was this translation helpful? Give feedback.
-
Due to the compiler not recognizing some error cases with explicit field layout (e.g. overlapping a reference type and a value type, which causes a TypeLoad exception at runtime) I could see this having to be restricted to just blittable types, in which case it might be worthwhile to tack onto that proposal (#187). It might also be worthwhile just tacking it onto blittable types, since blittable types will come with guarantees that would help with the definite assignment validation. |
Beta Was this translation helpful? Give feedback.
-
So if the struct has overlapping blittable fields but also a non-overlapped string field, I won't benefit from this? I'd rather this wasn't restricted to blittable types then. |
Beta Was this translation helpful? Give feedback.
-
For the "not recognizing some error cases" I was referring to the following case: [StructLayout(LayoutKind.Explicit)]
struct Magic
{
[FieldOffset(0)]
public string value;
[FieldOffset(0)]
public IntPtr handle;
} The compiler lets you do this today. However, the above causes a TypeLoadException at runtime. If this were allowed by the runtime, the compiler could detect that both value and handle are definitely assigned when one is assigned, as they have a "constant" size (both pointer size) and represent the same location in memory. However, there are other issues with supporting reference types/non-blittable explicit structs for definite assignment detection as well. For example:
The above struct is definitely assigned on x86 only when both fields are assigned, and it is a runtime exception in x64. But we do have a similar scenario for just blittable types, so maybe it doesn't matter:
The above is definitely assigned on x86 only when both fields are assigned, but is definitely assigned when |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Issue
Take the following program:
We define a struct with an explicit field layout that contains only primitive types (it would be considered
blittable
, when the feature comes around).We then declare an instance of the struct and set
value
to0.0
. This will end up making all fields definitely assigned; However, the compiler does not currently recognize this.Proposal
The compiler should either provide a way for the user to hint that the fields are definitely assigned or it should recognize explicit struct layouts and attempt to determine if the field is definitely assigned.
Beta Was this translation helpful? Give feedback.
All reactions