본문 바로가기
프로그래밍/c#

[C# 간단정리] Value Type vs. Reference Type

by ® 2020. 11. 17.
반응형

C#의 모든 타입은 아래 4가지로 분류된다.

1. Value types
2. Reference types
3. Generic type parameters
4. Pointer types

 

이 중 가장 기본이 되는 Value와 Reference type에 대해 알아보자.

 

Value type은 대부분의 내장 타입 (모든 숫자 타입, char type, bool type)과 struct나 enum으로 만들어진 커스텀 타입이다.

 

Reference type은 모든 class, array, delegate, interface, string이다.

 

둘의 가장 큰 차이는 메모리 관리이다. 예제를 통해 알아보자.

 

 

Value Types

value type 인스턴스의 할당은 항상 인스턴스를 복사한다.

public class Point { public int X, Y; }
static void Main()

{

    Point p1 = new Point();

    p1.X = 7;

    Point p2 = p1; // p1을 p2에 복사



    Console.WriteLine (p1.X); // 7

    Console.WriteLine (p2.X); // 7

    p1.X = 9; // Change p1.X

    Console.WriteLine (p1.X); // 9

    Console.WriteLine (p2.X); // 7

}

 

Reference Types

Reference type 변수의 할당은 객체 인스턴스 (object instance)를 복사하는 것이 아니라, 참조를 복사한다.

static void Main()

{

    Point p1 = new Point();

    p1.X = 7;

    Point p2 = p1; // p1의 참조를 p2에 복사



    Console.WriteLine (p1.X); // 7

    Console.WriteLine (p2.X); // 7

    p1.X = 9; // Change p1.X

    Console.WriteLine (p1.X); // 9

    Console.WriteLine (p2.X); // 9

}

 

반응형

'프로그래밍 > c#' 카테고리의 다른 글

C# 언어의 특징 - "객체 지향"편  (0) 2020.11.17

댓글