Language/C#

[C#] 구조체 (struct)

달별선장 2023. 9. 13. 07:46
728x90

클래스보다 상대적으로 가벼운 특징이 있다.

클래스와 같이 메서드, 프로퍼티 등 거의 비슷하 구조를 가지고 있다.

상속 불가

인터페이스 구현 가능

 

 

using System;

namespace HelloWorld
{
    class Program
    {
        // 구조체 선언
        struct ClassRoom // 명명규칙 : 대문자로 시작
        {
            //public string name; // Error : null 불가
            public string? name = null;
            public int age;
            public bool woman;
            
            // 생성자
            public ClassRoom(string? name, int age, bool woman)
            {
                this.name = name; // 선언된 필드는 반드시 초기화되어야 함
                this.age = age;     // (초기화) main 에서 호출한 parameter 값 대입
                this.woman = woman;  // (초기화) main 에서 호출한 parameter 값 대입
            }

            // 메서드
            public override string ToString()
            {
                return $"Her name is {name} \nand her age is {age} \nIs she woman? {woman}";
            }
        }

        static void Main(string[] args)
        {
            //ClassRoom classroom = new ClassRoom(null, null, null); // nullable 형식 아닌 변수에 null 할당 불가
            ClassRoom classroom = new ClassRoom(null, 30, false); // nullable 형식 아닌 변수에 null 할당 불가
            Console.WriteLine(classroom.ToString());
        }

        
    }
728x90