views:

157

answers:

3
+3  Q: 

use MORE structs?

There have been several questions over the past few days about the proper use of null; here are three (one is mine):

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"?

+1  A: 

The big limitation (IMO) of a struct is that it ought to be immutable.

I have several times defined and used a user-defined struct, for the reason you suggested (ie. because a struct can't be null); but I was then often (until I learned to never make them anything but immutable) burned by modifying a copy (sometimes an unnamed temporary copy) of a struct instance, instead of modifying the instance itself.

ChrisW
+3  A: 

I think you should just stick to the Null Object, being creative like this will just get you into trouble, and probably make the code less maintainable.

sylvanaar
A: 

If you start using structs in weakly types scenarios (like assigning to an object type) Object o = structValue; or Object o = new mystruct(); or Object o = default(mystruct); etc. the values are boxed onto the heap, and they are also unboxed when used. This is a potential drawback because it affects performance. See info from Microsoft about boxing and unboxing.

John K
You're less likely to need to do that with generics.
Dan
Yes, the one exception being generics can still be weakly typed - for example "List<object>" provides no advantage but still might be used to stored struct values and boxing/unboxing still occurs.
John K