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?
The Nullable<T> structure supports using only a value type as a nullable type because reference types are nullable by design. The Nullable class provides complementary support for the Nullable<T> structure.
Difference between Structs and Classes: Struct are value types whereas Classes are reference types. Structs are stored on the stack whereas Classes are stored on the heap. Value types hold their value in memory where they are declared, but a reference type holds a reference to an object in memory.
In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable. In this way, struct should be used only when you are sure that, It logically represents a single value, like primitive types (int, double, etc.). It is immutable.
Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With