값 타입(value type)으로, 스택(Stack) 에 저장된다.
→ 힙(Heap)에 저장되지 않기에 빠르게 작동 가능하다.
struct 구조체이름
{
// 필드 (멤버 변수)
public 데이터타입 변수명;
// 생성자 (선택사항)
public 구조체이름(매개변수들)
{
this.변수명 = 매개변수;
}
// 메서드 (선택)
public void 메서드명()
{
// 로직
}
}
✅ 구조체도 클래스처럼 필드와 메서드를 가질 수 있다.
✅ 생성자는 모든 필드를 초기화해야만 함
✅ 기본 생성자는 자동 제공되지만, 명시적으로 만들 수 없음
✅new없이도 생성 가능하나, 초기화되지 않으면 사용 불가
✅new Skill(...)방식 → 생성자 실행, 필드 초기화
Skill skill = new Skill();
// 모든 필드가 기본값으로 초기화됨
// 예: int → 0 / string → null / bool → false / float → 0.0f
C# 구조체는 기본 생성자(Skill())를 자동 생성하기 때문에,
우리가 직접public Skill() {}형태로 만들면 컴파일 에러 발생
enum Type { Normal, Elite, Boss }
struct Skill
{
public string name;
public float coolTime;
public int cost;
public float range;
public Skill(string name, float coolTime, int cost, float range)
{
this.name = name;
this.coolTime = coolTime;
this.cost = cost;
this.range = range;
}
}
struct Monster
{
public string name;
public Type type;
public int attackRange;
public float speeed;
public string[] items;
}
static void Main(string[] args)
{
// 1번 방법
Skill fireball = new Skill("파이어볼", 2.5f, 10, 3.5f);
// 2번 방법
Skill fireball;
fireball.name = "파이어볼";
fireball.coolTime = 2.5f;
fireball.cost = 10;
fireball.range = 3.5f;
Skill waterball;
waterball.name = "워터볼";
waterball.coolTime = 1.5f;
waterball.cost = 15;
waterball.range = 2.5f;
Monster orc;
orc.name = "오크";
orc.type = Type.Normal;
orc.items = new string[] { "포션", "장비" };
orc.attackRange = 10;
orc.speeed = 5.5f;
}