프로그래밍/C#

[C#] 박싱 / 언박싱 (boxing / unboxing)

Rolen 2023. 6. 21. 15:41

출력

Boxing = 값형(기본형) 데이터를 참조형으로 변환

Unboxing = 반대 개념이지만, Boxing 된 것을 기존의 데이터 형으로만 변환할 수 있다.

 

boxing 진행 -> 묵시적

unboxing 진행 -> 명시적

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Boxing_Unboxing
{
    internal class Boxing_Unboxing
    {
        static void Main(string[] args)
        {
            int foo = 526;
            object bar = foo;
            // foo -> bar Boxing
            Console.WriteLine(bar);
            try
            {
                double d = (short)bar;  // Boxing을 진행하기 전의 타입으로만 Unboxing이 가능하다.
                Console.WriteLine(d);
            } catch (InvalidCastException e)
            {
                Console.WriteLine(e + "Error"); // 위 코드는 에러가 발생한다.
            }
        }
    }
}
728x90