본문 바로가기

프로그래밍/C# 프로그래밍

클래스와 구조체의 차이 - c#

클래스와 구조체의 구분은 C++를 사용할때 부터 약간의 논의가 있었다.


실제로 C++에서의 구분은 거의 없다고 봐야하며, 디폴트 접근자가 private이냐 public 정도의 차이였다.


C# 에서의 msdn 가이드로 나온 부분을 보면 다음과 같다.


Classes and structs are two of the basic constructs of the common type system in the .NET Framework. Each is essentially a data structure that encapsulates a set of data and behaviors that belong together as a logical unit. The data and behaviors are the members of the class or struct, and they include its methods, properties, and events, and so on, as listed later in this topic.

A class or struct declaration is like a blueprint that is used to create instances or objects at run time. If you define a class or struct called PersonPerson is the name of the type. If you declare and initialize a variable p of typePersonp is said to be an object or instance of Person. Multiple instances of the same Person type can be created, and each instance can have different values in its properties and fields.

A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory. When the object reference is assigned to a new variable, the new variable refers to the original object. Changes made through one variable are reflected in the other variable because they both refer to the same data.

A struct is a value type. When a struct is created, the variable to which the struct is assigned holds the struct's actual data. When the struct is assigned to a new variable, it is copied. The new variable and the original variable therefore contain two separate copies of the same data. Changes made to one copy do not affect the other copy.

In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.

결정적으로 클래스는 레퍼런스 타입이고, 구조체는 밸류타입이다.

인스턴스를 생성한후, 좀 더 복잡한 행위나 데이터를  수정할 경우 클래스를..  메인 데이터를 수정하지 않는 작은 데이터를 다룰때 구조체를 사용하라고 나와 있다