프로그래밍/C#

[C#] 값 타입 vs 참조 타입(2)

갓똥 2020. 1. 30. 20:18
728x90
반응형

1. int (System.Int32)

using System;

class Program {
    public static void Main() {
        // int n = new int();
        
        int n1 = 1;
        int n2 = n1;
        
        n2 = 10;
        Console.WriteLine(n1);
    }
}

 

int는 값 타입일까? 참조 타입일까?
값 타입이라면 n2는 10이 될 것이고, 참조 타입이라면 n2는 1이 될 것이다.
int의 정의를 따라가면 int는 struct로 만들어 진것을 볼 수 있다.
따라서 값 타입으로 n2는 10이 된다.

 


2. array (System.Array)

using System;

class Program {
    public static void Main() {
        int[] arr1 = {1, 2, 3};
        int[] arr2 = arr1;
        
        arr2[0] = 10;
        Console.WriteLine(arr1[0]);
    }
}

 

위의 코드에서 arr2 = arr1; 에서 arr1의 배열을 그대로 복사할까?
그림으로 값 타입일 경우와 참조 타입일때의 모습을 보자.

위의 그림은 위는 값 타입일 경우, 아래 그림은 참조 타입일 경우의 모습을 나타냈다.
Int와 마찬가지로 array에서 정의로 이동해보면 array는 class인 것을 확인할 수 있다.
따라서 아래 그림이며 결과값은 10임을 볼 수 있다.

 


3. string (System.String)

using System;

class Program {
    public static void Main() {
        string s1 = "Hello";
        string s2 = s1;
        
        s2 = "world";
        Console.WriteLine(s1);
    }
}

 

마지막으로 string이다.
바로 정의로 이동해보면 string은 class인 것을 알 수 있다.
그렇다면 모습은 아래 그림처럼 될 것이다.

따라서 결과값은 world가 나와야 정상일 것 같다.
하지만 결과를 출력해보면 여전히 "Hello"가 찍히는 것을 볼 수 있다.
왜 이런 결과가 나오게 되는 걸까?
사실 아래에 써있다시피 s2 = "world" 의 의미가 다르다.
using System;

class Program {
    public static void Main() {
        string s1 = "Hello";
        string s2 = s1;
        
        s2 = "world"; // s2 = new stirng("world");
        Console.WriteLine(s1);
    }
}

 

그림으로 보면 아래와 같다.

 


4. value type / referece type 을 조사하는 방법

using System;

class Program {
    public static void Main() {
        int[] arr = {1, 2, 3};
        
        Type t = arr.GetType();
        
        Console.WriteLine(t.IsValueType);
        
        
        int n = 1;
        
        Type t2 = n.GetType();
        
        Console. WriteLine(t2.IsValueType);
    }
}

 ① value type / referece type을 조사하는 방법

    => C#의 모든 타입에는 GetType() 메소드가 있다.

    => Type 클래스의 isValueType 속성으로 확인

728x90
반응형