13

I have a simple struct which contains two fields; one stores an object and the other stores a DateTime. I did this because I wanted to store objects in a Dictionary but with a DateTime stamp as well.

I've got a method which returns my structure, and I've now decided the method should also be able to return null, so I made my structure nullable. I'm now wondering if I should just make my structure a class so it's a reference type?

Charlie
  • 10,227
  • 10
  • 51
  • 92

2 Answers2

10

In this case, yes, it's probably clearer to make your structure a class.

As far as justification goes, you're essentially creating a specialized Tuple. It's interesting to note that the library designers have opted to make the .Net 4 Tuple a class rather than a struct. (That page is the tuple creator and links to the various tuple instance classes)

Greg D
  • 43,259
  • 14
  • 84
  • 117
  • 3
    The "tuple as a class" is probably mainly to keep things consistent when you get to Tuple<,,,,,,,> (8 args) - which would almost certainly be oversized as a struct - especially if any of the T are non-trivial. – Marc Gravell Jun 12 '09 at 12:15
  • @Marc: That's a good point. I hadn't noticed until just now that the Tuples are immutable. – Greg D Jun 12 '09 at 12:54
6

Either should be fine, in reality (as long as the struct is immutable). A DateTime and a reference shouldn't be enough to make it oversized.

I assume you are using it as the value (not the key) in the dictionary? If used as the key you would need to override Equals and GetHashCode(), regardless of struct vs class.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Yep, am using it as value, not key, so am overriding those methods. – Charlie Jun 12 '09 at 12:20
  • 1
    (maybe I didn't phrase it well... those methods are only important [in this context] when used as a key) – Marc Gravell Jun 12 '09 at 12:22
  • Yes, I understand - not needed for me. You mean if you're using the class as a key, as someone explained in one of the answers here http://stackoverflow.com/questions/689940/hashtable-with-multidimensional-key-in-c – Charlie Jun 12 '09 at 13:04