Microsoft MVP성태의 닷넷 이야기
닷넷: 2344. C#의 Identity conversion 의미 [링크 복사], [링크+제목 복사],
조회: 91
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C#의 Identity conversion 의미

오호~~~ 이런 용어가 있었군요.

10.2.2 Identity conversions
; https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/conversions#1022-identity-conversion

An identity conversion converts from any type to the same type or a type that is equivalent at runtime.

// 번역은 "항등 변환" 정도가 적당할 것 같습니다.


일반적인 상황이라면 T 타입에서 T 타입으로의 변환을 의미합니다. 즉, 같은 타입에 대한 변환이라 no-op 연산에 해당하는데, 단지 컴파일러 입장에서는 "같은 타입"이라고 판단할 수 없는 경우가 "dynamic"의 등장으로 발생했다고 합니다. 그래서 "at runtime"이라는 조건이 붙어 있는 것입니다.

문서에 따르면 이와 관련해 5개의 변환 유형이 있다고 하는데요, 하나씩 예제와 함께 다뤄보겠습니다. ^^


1. Between T and T, for any type T.

T와 T 사이의 변환이라 더 설명할 것이 없군요. ^^

int i = 10;
int j = i; // Identity conversion


2. Between T and T? for any reference type T.

참조형 타입의 T에 대해 T? 타입 간의 변환입니다.

string text = "Hello, World!";
string? text2 = text; // Identity conversion

"Identity conversion"의 특징 중 하나가 바로 암시적 형변환이라는 점인데요, 그렇다면 왜 "참조형"으로 제한이 된 것일까요? 가령, 값 형식에서도 이렇게 암시적 형변환이 가능한데 그럼 이것을 "Identity conversion"이라고 볼 수 있을까요?

int number = 42;
int? number2 = number; // 값 형식의 경우에도 암시적 형변환이 가능

// 10.2.9 Boxing conversions

그럴 수 없는 것이, Identity conversion의 또다른 특징으로 "대칭"적이어야 한다는 점입니다. 즉, 참조형의 경우에는 T와 T? 간의 대칭 변환이 가능하지만,

string text = "Hello, World!";

string? text2 = text; // 대칭 변환이 가능한 Identity conversion
string text3 = text2;

값 형식의 경우에는 그것이 불가능합니다.

int number = 42;

int? number2 = number;
int number3 = number2; // 컴파일 오류 - error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)


3. Between object and dynamic.

이전에 언급했듯이, 컴파일 시점에는 같은 타입이라고 볼 수 없지만 런타임 시에는 동일한 타입으로 판단되는 대표적인 예입니다. 물론, 이것도 암시적/대칭 변환이 가능합니다.

object obj = "Hello, World!";

dynamic dyn = obj; // Identity conversion
object obj2 = dyn;


4. Between all tuple types with the same arity, and the corresponding constructed ValueTuple<...> type, when an identity conversion exists between each pair of corresponding element types.


튜플인 경우, 1) 같은 수의 요소를 가지고 2) 그 개별 요소가 대응하는 타입이 또한 "Identity conversion" 관계라면 튜플 역시 "Identity conversion"이 허용됩니다.

{
    (int a, string b) t1 = (1, "two"); // Identity conversion
    (int c, string d) t2 = t1;
}

또한, 이 규칙은 재귀적으로 적용됩니다.

((int a, string b) t1, int) t4 = (t1, 7); // Identity conversion
((int c, string d) t2, int) t5 = (t2, 8);


5. Between types constructed from the same generic type where there exists an identity conversion between each corresponding type argument.


튜플과 유사하게, 제네릭도 대응하는 형식 인자 간의 Identity conversion이 가능하다면 제네릭 타입 간에도 Identity conversion이 허용됩니다.

List<dynamic> dns = new List<dynamic>();

List<object> obj = dns; // object와 dynamic 간 Identity conversion이 가능하므로
                              // 제네릭 타입 간에도 Identity conversion이 가능
List<dynamic> dns2 = obj;

이처럼 2개의 타입 간에 Identity conversion이 가능하다면, 그 타입들은 "identity convertible"한 것입니다.




혹시 암시적/대칭 변환이 존재한다고 해서 그것을 "Identity conversion"이라고 부를 수 있을까요? 가령, 아래와 같은 2개의 타입도,

public class Kilogram
{
    public decimal Weight { get; set; }

    public Kilogram(decimal weight)
    {
        Weight = weight;
    }

    public static implicit operator Kilogram(Gram g)
    {
        return new Kilogram(g.Weight / 1000);
    }
}

public class  Gram
{
    public decimal Weight { get; set; }

    public Gram(decimal weight)
    {
        Weight = weight;
    }

    public static implicit operator Gram(Kilogram kg)
    {
        return new Gram(kg.Weight * 1000);
    }
}

서로 암시적/대칭 변환이 가능하지만,

Kilogram kg1 = new Kilogram(1);
Gram g1 = kg1; // 암시적 형변환
Kilogram kg2 = g1; // 대칭 형변환

이것은 또다른 유형으로 분류된, 즉 "10.5 User-defined conversions"에 해당하는 것일 뿐 "Identity conversion"에는 속하지 않습니다. 그러니까, 위에서 소개했던 5가지 유형에 해당하는 것만 항등 변환인 것입니다.




그나저나, 저런 문서를 보면서 느낀 건데... 프로그래밍 언어라는 것이 이렇게나 세세한 부분까지 규칙을 정의하고 그에 따라 컴파일러가 동작하도록 만든다는 점에서 참 대단하다는 생각이 듭니다. 다른 한편으로는, 뭐랄까... 좀 질리게 하는 면이 있는 것도 같고. ^^;




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/21/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12842정성태10/1/202135822오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/202118668스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/202117598.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/202121081.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/202120186.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/202116665VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/202117043Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/202118754.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/202118260오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/202114796VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/202118366VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/202114029VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/202119857오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
12829정성태9/5/202120824.NET Framework: 1115. C# 10 - (14) 구조체 타입에 기본 생성자 정의 가능파일 다운로드1
12828정성태9/4/202117048.NET Framework: 1114. C# 10 - (13) 단일 파일 내에 적용되는 namespace 선언파일 다운로드1
12827정성태9/4/202118243스크립트: 27. 파이썬 - 웹 페이지 데이터 수집을 위한 scrapy Crawler 사용법 요약
12826정성태9/3/202122381.NET Framework: 1113. C# 10 - (12) 문자열 보간 성능 개선 [1]파일 다운로드1
12825정성태9/3/202117370개발 환경 구성: 603. GoLand - WSL 환경과 연동
12824정성태9/2/202126639오류 유형: 760. 파이썬 tensorflow - Dst tensor is not initialized. 오류 메시지
12823정성태9/2/202116616스크립트: 26. 파이썬 - PyCharm을 이용한 fork 디버그 방법
12822정성태9/1/202121701오류 유형: 759. 파이썬 tensorflow - ValueError: Shapes (...) and (...) are incompatible [2]
12821정성태9/1/202115942.NET Framework: 1112. C# - .NET 6부터 공개된 ISpanFormattable 사용법
12820정성태9/1/202118273VC++: 147. Golang - try/catch에 대응하는 panic/recover [1]파일 다운로드1
12819정성태8/31/202118697.NET Framework: 1111. C# - FormattableString 타입
12818정성태8/31/202115128Windows: 198. 윈도우 - 작업 관리자에서 (tensorflow 등으로 인한) GPU 연산 부하 보는 방법
12817정성태8/31/202119145스크립트: 25. 파이썬 - 윈도우 환경에서 directml을 이용한 tensorflow의 AMD GPU 사용 방법
... [46]  47  48  49  50  51  52  53  54  55  56  57  58  59  60  ...