posts - 916, comments - 758, trackbacks - 11

My Links



Post Categories

Misc. Coding

To struct or not to struct

I've been commenting on this post by Bernal Schooley on a method using structs to 'simplify' using ViewState. Bernal has had a couple of posts around ViewState and methods of making it's use simpler. I have to say the comments on the posts are more useful for me that the posts themselves (as is often the way...comments are still on the blog right ).
One problem I do have is advocating the use of structs for this don't get me wrong, I am aware of some advantages around structs; which go away slightly when using Generics as the constant boxing/unboxing no longer happens...There does seem to be a lot of misunderstanding around structs though...they're not always faster!
Structs are stored on the stack rather than the heap, this makes accessing and using them faster (often dramatically faster!) . However you have to be aware of the limitations around biggie is that over 16 bytes you lost a lot of the advantage of this speedup - don't be storing a ton of data in a struct (well, not a ton...over 16 bytes!).
The other biggie is boxing structs...again in this case you've flipping them onto the heap rather than the you lose the 'stack' advantage again...
So, story is structs can be great but be careful with them...there's a newbie mistake in thinking that structs are these great, lightweight objects you can use however you want...they're not. Unless you can *really* justify using a struct, don't bother! In my entire .NET programming career I used structs maybe 5 times...and for very specific reasons!

Print | posted on Tuesday, October 09, 2007 11:15 AM | Filed Under [ .NET Patterns ]


# re: To struct or not to struct

Hi Scott, I'll start by admitting my understanding of the heap/stack details are lacking, so over the next day or so I'll read up a bit on it. I also, have seldom ever used them.

Since the point of the ViewStateStruct is a one off data container, I don't think the "to struct or not to struct" is all that important in the given context.

Simply changing "struct" to "class" works for the ViewState data container.

None-the-less, if I can find documentation on struct's that indicates it shouldn't be used in this scenario, then I'll update my article.

10/9/2007 12:16 PM | Bernal Schooley

# re: To struct or not to struct

Bernal, absolutely...I wasn't specifically criticising your post. All I am commenting on is the misuse of Structs in general - your technique is really interesting, all I'm saying is that a struct in that case isn't really worse or better than an reference type...

10/9/2007 2:35 PM | Scott Galloway

# re: To struct or not to struct

THank you .

7/2/2009 8:53 AM | tolga

# re: To struct or not to struct

THank you informaiton

7/2/2009 9:15 AM | sxe

Comments have been closed on this topic.

Powered by: