Richard
Richard

Reputation: 449

Keeping a struct as a value type - What types can I use / return?

I want to store a lot of little items (well, a few thousand) of 3 or so byte values, so I am thinking of using a struct. What I am unsure about is how to keep it as a value type, for example, if I just store the 3 bytes as bytes and override ToString(), GetHashCode() and Equals(), it will stay a value type, right? But what about if I want to return the 3 bytes as a list (return, not store!), so I do

public List<byte> GetValues
    {
      get
        {
             return new List<byte>(3) { byte1, byte2, byte3 };
        }
    }

..but would this now mess it up? Would part of this struct's data now be on the heap?

I did read somewhere about this stuff, but I can't remember where and can't find it again.

Thanks for any advice you can give me.

Richard

Upvotes: 1

Views: 97

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501606

No, that's just a property - the list is created when the property is accessed, but that's all. You haven't declared any extra fields within your type.

Even if you did declare a field of type List<byte>, your type would still be a value type - all structs are value types - it's just that one of the fields would have a value which is a reference. That's relatively uncommon, but not unheard of.

Upvotes: 2

Related Questions