PROGRAMING/C#

Struct VS Class in C#

파란실버라이트 2013. 7. 25. 11:30

클래스 및 구조체는 .NET Framework 공용 형식 시스템의 두 가지 기본 구문입니다. 클래스 및 구조체는 본질적으로 하나의 논리 단위에 속하는 일련의 데이터와 동작을 캡슐화하는 데이터 구조입니다. 데이터 및 동작은 클래스 또는 구조체의 멤버로 이 항목의 뒷부분에서 설명하는 메서드, 속성, 이벤트 등이 여기에 해당합니다.

 

클래스 또는 구조체 선언은 런타임에 인스턴스 또는 개체를 만드는 데 사용되는 청사진과 같습니다. Person이라는 클래스 또는 구조체를 정의하는 경우 Person은 해당 형식의 이름이 됩니다. Person 형식의 변수 p를 선언하고 초기화하는 경우 pPerson의 개체 또는 인스턴스라고 합니다. 동일한 Person 형식의 인스턴스를 여러 개 만들 수 있으며 각 인스턴스의 속성 및 필드는 서로 다른 값을 가질 수 있습니다.

 

클래스는 참조 형식입니다. 클래스의 개체를 만드는 경우 개체가 할당된 변수에는 해당 메모리에 대한 참조만 포함됩니다. 개체 참조가 다른 변수에 할당되면 새 변수는 원래 개체를 참조합니다. 두 변수는 동일한 데이터를 참조하므로 한 변수를 통해 변경된 내용은 다른 변수에도 적용됩니다.

 

구조체는 값 형식입니다. 구조체를 만드는 경우 구조체가 할당된 변수에는 구조체의 실제 데이터가 포함됩니다. 구조체를 새 변수에 할당하면 해당 구조체가 복사되므로 새 변수와 원래 변수는 동일한 데이터의 별도 복사본을 보유하게 됩니다. 한 복사본이 변경되어도 다른 복사본은 영향을 받지 않습니다.

 

클래스는 클래스 개체를 생성한 후 수정하려고 하는 데이터나 더 복잡한 동작을 모델링하는 데 사용됩니다.

구조체는 구조체를 생성한 후 수정하지 않을 데이터를 주로 포함하는 작은 데이터 구조에 더 적합합니다.  

 

 

 

When to use structs

So you've seen how structs and classes differ. Here's when structs 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 structs:

  • 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 a struct should ideally be below 16 bytes, but it really is up to you. In case your struct 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.

 

 

참조 : http://www.codeproject.com/Articles/8612/Structs-in-C