views:

348

answers:

6

I have a type which I consider use it as struct.

  • It represents single value
  • It is immutable

But the problem is, it has 6 fields of int.

So which solution I should use for this type?

  1. keep using struct?
  2. change to class?
  3. or pack 6 integers into an array of int, so it has only one field

EDIT

Size of struct with 6 integer fields is 24 bytes, which is huge to pass around. Recommend size for struct is not more than 16 bytes

A: 

Without seeing your struct, it's difficult to say anything definitively. But I suspect you should leave this as a struct.

Software Monkey
A: 

How about a WriteOnce<int[]> ?

Dmitri Nesteruk
@Dmitri Nesteruk: could you explain please?
Mitch Wheat
+4  A: 

It depends how you are going to use it?

  1. Are you going to allocate a lot of it vs. pass it around a lot?
  2. Is it going to be consumed by 3rd party code? In this case, classes typically give you more flexibility.
  3. Do you want struct vs. class semantics? For example, non-nullable?
  4. Would you benefit from having a couple of pre-created instances of this class that can be re-use to represent special cases? Similar to String.Empty. In this case you would benefit from a class.

It is hard to answer just from the information you provided in your question.

vboctor
1. Pass around a lot2. Not going to used by 3rd party code3. No4. No
chaowman
It looks to me that a class is probably the right choice for you. This is mainly based on your answer to question #1 and #3.
vboctor
+1  A: 

Be careful of boxing. If your struct is going to be consumed by a method which expects an Object, it will be coerced into an object and you'll have a potential performance hit.

Here's a reference that explains it in more detail.

I'd make it a class (#2) and then you wouldn't have to worry about it.

Using an array of six integers (#3) would probably make your code harder to read. A class with descriptive identifiers for each int would be much better.

Dana Robinson
A: 

In general, when storing more than two pieces of related data I like to make a class that binds them together. Especially if I will be passing them around as a unit.

Chris Nava
I think you've missed the point of the question - it isn't a case of whether or not to keep them together, it's whether to use a struct or a class.
Jon Skeet
A: 

I would suggest writing a little benchmark to measure the performance of the different options, this is the only way to know for sure. You may be surprised at the results (I often am).

(I'm assuming that your concern here is performance.)

pauldoo