클래스 및 구조체는 .NET Framework 공용 형식 시스템의 두 가지 기본 구문입니다.
When to use structs
So you've seen how struct
s and class
es differ. Here's when struct
s are better:
- You want your type to look and feel like a primitive type.
- You create a lot of instances, use them briefly, and then drop them. For e.g., within a loop.
- The instances you create are not passed around a lot.
- You don't want to derive from other types or let others derive from your type.
- You want others to operate on a copy of your data (basically pass by value semantics).
Here's when not to use struct
s:
- The size of the
struct
(the sum of the sizes of its members) gets large. The reason is that beyond a particular size, the overhead involved in passing it around gets prohibitive. Microsoft recommends that the size of astruct
should ideally be below 16 bytes, but it really is up to you. In case yourstruct
has reference types as members, make sure you don't include the size of instances of reference types, just the size of the references. - You create instances, put them in a collection, iterate and modify elements in the collection. This will result in a lot of boxing/unboxing as FCL Collections operate on
System.Object
. Every addition will involve a boxing operation, and every modification will involve an unboxing followed by a boxing operation.
Conclusion
Some of the inefficiencies of using value types will go away with generics in C# 2.0, particularly when using collections, so things can only get better. It's great that C# allows you to choose how you want to implement your type, as a value or a reference type. Judicious use of value types can greatly increase application performance. Hopefully, this article will help you do that.