클래스와 차이점
기본 생성자 재정의 못함
생성자에서 모든 멤버를 명시적으로 초기화 해야 함
public struct Point
{
int x = 1; // Illegal: 필드 이니셜라이저
int y;
public Point() {} // Illegal: 매개변수가 없는 생성자
public Point (int x) {this.x = x;} // Illegal: 필드를 할당해야함
}
public struct Point
{
int x, y;
public Point (int x, int y) { this.x = x; this.y = y; }
}
...
Point p1 = new Point (); // p1.x and p1.y will be 0 암것도 안 쓰면 걍 0(디폴트 값)임 (Point p1 = default;)
Point p2 = new Point (1, 1); // p2.x and p2.y will
Point p1 = default;
default 키워드는 기본 생성자와 같은 일을 함
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
이 키워드가 붙으면 readonly 만 불러올 수 있다
값 형식임에도 스택 영역에 올라갈 수 있다
구조체의 인스턴스는 변수가 어디 선언 됐는지에 따라 힙 영역인지 스택영역인지 결정된다.
지역 변수나 파라미터인 경우 스택영역
클래스의 멤버일 경우 힙영역
'Stack 영역'
void SomeMethod()
{
Point p; // p will reside on the stack
}
struct Point { public int X, Y; }
'구조체의 배열 또한 힙 영역'
class MyClass
{
Point p; // Lives on heap, because MyClass instances live on the heap
}
'ref struct 는 인스턴스가 스택 영역에만 존재하도록 제한한다.'
var points = new Point [100]; // Error: will not compile!
ref struct Point { public int X, Y; }
class MyClass { Point P; } // Error: will not compile!