简体   繁体   中英

Nullable struct vs class

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?

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM