1

In situations like this:

public struct SectorLocator
{
    public Surface Side { get; init; } //this is an enum-int

    public VerticalPortion Section { get; init; } //this is another enum-int
}


public struct DataLocator
{

    public SectorLocator Sector{get; init;}

    public MeasureType Measure { get; init; } //this is another enum-int;

}

is DataLocator still a value-type? Or it's like when you put a reference type inside a struct? How does Sector property behave when you pass it as an argument?

I didn't found any answer clear enough about this.

DrkDeveloper
  • 939
  • 7
  • 17
  • Does this answer your question? [Can structs contain fields of reference types](https://stackoverflow.com/questions/945664/can-structs-contain-fields-of-reference-types) – Johnathan Barclay May 10 '21 at 15:54
  • Thanks, but I don't think so. My question is about how SectorLocator property is handled. Is a reference? or is it still a value type? – DrkDeveloper May 10 '21 at 16:00

1 Answers1

2

Yes, DataLocator is still a value-type; that is defined fully from the struct term. A value-type can contain references, but that doesn't change anything about how it behaves, other than: you're not allowed to use it in an unmanaged constraint if it does contain references (and some APIs like Unsafe/MemoryMarshal etc may refuse to play with you). This is effectively the same as asking System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences<T>(): this will return false for a value-type that does not contain references, and true for any other scenario.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • But that SectorLocator property inside DataLocator is a reference or is a raw value? That's my question. I know is irrelevant because are init-only, but I want to learn and know more. – DrkDeveloper May 10 '21 at 15:58
  • @DrkDeveloper `SectorLocator` is a value-type, so `DataLocator` literally contains the *value* of `SectorLocator`; if `SectorLocator` takes 20 bytes, then `DataLocator` will presumably be 24 (4 bytes for the integer) (plus padding if needed). A non-boxed reference to a `SectorLocator` is a `ref SectorLocator`, and you can't store that in fields of either a class or a struct, except *sort of* in a `ref struct`, via a *span*. – Marc Gravell May 10 '21 at 16:04
  • @MarkGravell That's the answer I want to hear. Sorry if the question was unprecise. Thank you so much. – DrkDeveloper May 10 '21 at 16:07