There have been several questions over the past few days about the proper use of null; here are three (one is mine):
- Best Practice: Should functions return null or an empty object?
- null objects vs. empty objects
- how do i explain that if (xyz == null) checks are not “protective”.
While reading and thinking about this issue, the thought occured to me: why not use struct instead of class? (I then read some of the many questions about just that.)
One big benefit of a struct (in this context) is that it can't be null, so there is never a need to check against null. And as an added bonus, if you really want a null struct you can do that too with some extra syntax (T?) and the Nullable<> type. (Too bad reference types didn't work like this too!)
But structs are passed by value which kills performance. Well, first, code should be "right" (whatever that might mean) and then fast. However, there are several ways to avoid that overhead where it really matters: ref parameters, nullable parameters, place the struct in some other class, say List<>.
True, with structs, you can't create a class hierarchy, but "inheritence is overused". And you can implement interfaces.
Using more struct-based objects could make writing multi-threaded code easier.
Are there any more infrequently cited advantages to structs? Do any of these considerations even come close to putting a dent in class's massive "head start"?