Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 구조체(Struct)를 생성하는 방법 총정리

C#에서 구조체(structure)는 값 형식(value type) 데이터 타입입니다. 구조체를 활용하면 하나의 변수에 서로 다른 데이터 타입의 연관된 데이터들을 함께 담을 수 있습니다. C#에서는 struct 키워드를 사용하여 구조체를 생성합니다.

구조체를 정의하려면 반드시 struct 문을 사용해야 합니다. struct 문은 프로그램에서 사용할 수 있는 새로운 데이터 타입을 정의하며, 이 데이터 타입은 하나 이상의 멤버(member)로 구성됩니다.

예를 들어, 도서 정보를 담는 Books 구조체는 다음과 같이 선언할 수 있습니다.

struct Books {
    public string title;
    public string author;
    public string subject;
    public int book_id;
};

구조체 생성 예제

다음 예제는 C#에서 구조체를 선언하고, 멤버에 값을 할당한 뒤 출력하는 전체 과정을 보여줍니다.

using System;
struct Books {
public string title;
    public string author;
    public string subject;
    public int book_id;
};
public class testStructure {
    public static void Main(string[] args) {
        Books Book1; /* Book1을 Book 타입으로 선언 */
        Books Book2; /* Book2를 Book 타입으로 선언 */
        /* book 1 정보 설정 */
        Book1.title = "C Programming";
        Book1.author = "Nuha Ali";
        Book1.subject = "C Programming Tutorial";
        Book1.book_id = 6495407;
        /* book 2 정보 설정 */
        Book2.title = "Telecom Billing";
        Book2.author = "Zara Ali";
        Book2.subject = "Telecom Billing Tutorial";
        Book2.book_id = 6495700;
        /* Book1 정보 출력 */
        Console.WriteLine( "Book 1 title : {0}", Book1.title);
        Console.WriteLine("Book 1 author : {0}", Book1.author);
        Console.WriteLine("Book 1 subject : {0}", Book1.subject);
        Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
        /* Book2 정보 출력 */
        Console.WriteLine("Book 2 title : {0}", Book2.title);
        Console.WriteLine("Book 2 author : {0}", Book2.author);
        Console.WriteLine("Book 2 subject : {0}", Book2.subject);
        Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
        Console.ReadKey();
    }
}

실행 결과

Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id :6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

핵심 포인트 정리

  • 구조체는 값 형식(value type)이므로 변수에 할당될 때 데이터가 복사됩니다.
  • struct 키워드를 사용하여 새로운 데이터 타입을 정의합니다.
  • 여러 개의 서로 다른 자료형 멤버(string, int 등)를 하나의 단위로 묶어 관리할 수 있습니다.
  • 클래스와 달리 상속은 지원하지 않지만, 간단한 데이터 그룹화에는 메모리 측면에서 유리합니다.