开发者

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):

  • 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开发者_JAVA技巧 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"?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜