Here's a fun one. When should you use struct and not class in C#?
I came across these rules here:
- a struct should represent a single value
- a struct should have a memory footprint less than 16 bytes
- a struct should not be changed after creation
Do you agree?
EDIT: I'm looking for more than a "struct is a value type" answer. =D
EDIT2: The way I've been thinking of it now is to use structs in times when the item is merely a collection of value types. A way to logically hold them all together into a cohesive whole
-
Use a struct when you want value semantics as opposed to reference semantics.
Edit
Not sure why folks are downvoting this had two already but this is a valid point, and was made before the op clearified his question, and it is the most fundamental basic reason for a struct.
if you need reference semantics you need an object not a struct.
DannySmurf : Everyone knows that. Seems like he's looking for more than a "struct is a value type" answer.BobbyShaftoe : Not everyone knows that. That is clearly one case.JoshBerke : It the most basic case and should be stated for anyone who reads this post and doesn't know that.DannySmurf : Not that this answer isn't true; it obviously is. That's not really the point.DannySmurf : @Josh: For anyone who doesn't know it already, simply saying it is an insufficient answer, since it's quite likely they don't know what it means, either.Daniel Earwicker : I've just downvoted this because I think one of the other answers should be at the top - any answer that says "For interop with unmanaged code, otherwise avoid". -
Whenever you don't need polymorphism, want value semantics, and want to avoid heap allocation and the associated garbage collection overhead. The caveat, however, is that structs (arbitrarily large) are more expensive to pass around than class references (usually one machine word), so classes could end up being faster in practice.
-
Structs can be useful in serial communications and COM interaction.
I don't feel you need to stick to those specific guidelines, it also depends on how you want to manage your memory.
Pop Catalin : +1, Add when performance is needed for large data sets. (Games, physics, rendering, and other more or less related stuff...) -
I think a good first approximation is "never".
I think a good second approximation is "never".
If you are desperate for perf, consider them, but then always measure.
Franci Penov : I would disagree with that answer. Structs have a legitimate use in many scenarios. Here's an example - marshaling data cross processes in atomic manner.Brian : Good point, interop/marshalling is another good reason.Erik Forbes : You should edit your post and elaborate on your points - you've given your opinion, but you should back it up with why you take this opinion.Greg : I think they need an equivalent of the Totin' Chip card (http://en.wikipedia.org/wiki/Totin%27_Chip) for using structs. Seriously. -
I can only agree with the first item, structs are used a lot in game programming for example
Alex Baranosky : they make games in C#?Refracted Paladin : Yes, well parts of them anyway. I know it is used for portions of games, like NWN2 World Creator. C is still usually at the core(engine). XNA Game Studio, Google it :)Rob : This answer doesn't explain what it is about structs that warrant their use in that situation.BlackTigerX : there are quite a few commercial games written in C#, the point is that they are used for optimized codeChris D. : Structures provide better performance when you have small collections of value-types that you want to group together. This happens all the time in game programming, for example, a vertex in a 3D model will have a position, texture coordinate and a normal, it is also generally going to be immutable. A single model may have a couple thousand vertices, or it may have a dozen, but structs provide less overhead overall in this usage scenario. I have verified this through my own engine design. -
System.Drawing.Rectangle
violates all three of these rules.Erik Forbes : Nobody said the BCL implementors did it right. =P -
Structs are good for atomic representation of data, where the said data can be copied multiple times by the code. Cloning an object is in general more expensive than copying a struct, as it involves allocating the memory, running the constructor and deallocating/garbage collection when done with it.
-
You need to use a "struct" in situations where you want to explicitly specify memory layout using the StructLayoutAttribute - typically for PInvoke.
Edit: Comment points out that you can use class or struct with StructLayoutAttribute and that is certainly true. In practice, you would typically use a struct - it is allocated on the stack vs the heap which makes sense if you are just passing an argument to an unmanaged method call.
Stephen Martin : The StructLayoutAttribute can be applied to structs or classes so this is not a reason to use structs. -
First: Interop scenarios or when you need to specify the memory layout
Second: When the data is almost the same size as a reference pointer anyway.
-
With the exception of the valuetypes that are used directly by the runtime and various others for PInvoke purposes, you should only use valuetypes in 2 scenarios.
- When you need copy semantics.
- When you need automatic initialization, normally in arrays of these types.
-
I use structs for packing or unpacking any sort of binary communication format. That includes reading or writing to disk, DirectX vertex lists, network protocols, or dealing with encrypted/compressed data.
The three guidelines you list haven't been useful for me in this context. When I need to write out four hundred bytes of stuff in a Particular Order, I'm gonna define a four-hundred-byte struct, and I'm gonna fill it with whatever unrelated values it's supposed to have, and I'm going to set it up whatever way makes the most sense at the time. (Okay, four hundred bytes would be pretty strange-- but back when I was writing Excel files for a living, I was dealing with structs of up to about forty bytes all over, because that's how big some of the BIFF records ARE.)
-
I use them sometimes for string valued "enums".
-
Nah - I don't entirely agree with the rules. They are good guidelines to consider with performance and standardization, but not in light of the possibilities.
As you can see in the responses, there are a log of creative ways to use them. So, these guidelines need to just be that, always for the sake of performance and efficiency.
In this case, I use classes to represent real world objects in their larger form, I use structs to represent smaller objects that have more exact uses. The way you said it, "a more cohesive whole." The keyword being cohesive. The classes will be more object oriented elements, while structs can have some of those characteristics, their on a smaller scale. IMO.
I use them a lot putting in Treeview and Listview tags where common static attributes can be accessed very quickly. I would struggle to get this info another way. For example, in my database applications, I use a Treeview where I have Tables, SPs, Functions, or any other objects. I create and populate my struct, put it in the tag, pull it out, get the data of the selection and so forth. I wouldn't do this with a class!
I do try and keep them small, use them in single instance situations, and keep them from changing. It's prudent to be aware of memory, allocation, and performance. And testing is so necessary.
-
I rarely use a struct for things. But that's just me. It depends whether I need the object to be nullable or not.
(Minor Edit): Like it was stated above, I use classes for real-world objects. I also have the mindset of structs are used for storing small amounts of data.
I hope this helps, I'm sorta new here.
-
Chapter 7 of Effective C# has some good stuff about when to use struct in C#
-
I do not agree with the rules given in the original post. Here are my rules:
1) You use structs for performance when stored in arrays. (see also http://stackoverflow.com/questions/597259/when-are-structs-the-answer/598182#598182)
2) You need them in code passing structured data to/from C/C++
3) Do not use structs unless you need them: a) They behave different from the normal objects under assignment and when passing as arguments, which can lead to unexpected behavior; this is particularly dangerous if the person looking at the code does not know he is dealing with a struct. b) They cannot be inherited. c) Passing structs as arguments is more expensive than classes.
-
Another situation where you should use structs is when your objects don't need identity.
-
You use structs when you don't want to inherit your class. This is great if you want to make objects that only hold datas.
0 comments:
Post a Comment