Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable struct vs class

Tags:

c#

.net

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?

like image 490
Charlie Avatar asked Jun 12 '09 12:06

Charlie


People also ask

Can a struct be nullable?

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.

What is difference between struct and class?

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.

When should I use a struct instead of a class?

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.

What is difference between struct and class in C#?

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.


1 Answers

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)

like image 129
Greg D Avatar answered Nov 10 '22 02:11

Greg D