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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...
NoWriterDateCnt.TitleFile(s)
13674정성태7/13/202410465오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/202412646닷넷: 2275. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
13672정성태7/10/20248610닷넷: 2274. IIS - (프로세스 종료 없는) AppDomain Recycle
13671정성태7/10/20249064오류 유형: 914. Package ca-certificates is not installed.
13669정성태7/9/20249305오류 유형: 913. C# - AOT StaticExecutable 정적 링킹 시 빌드 오류
13668정성태7/8/20249522개발 환경 구성: 716. Hyper-V - Ubuntu 22.04 Generation 2 유형의 VM 설치
13667정성태7/7/20247705닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/202410178Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/202410226Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20249211닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20248957닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20248786Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/202410056오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20249606개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/202410633개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20249277닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/202410338Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20249830닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20249497오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20249624닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/202411680닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/202410832닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/202410975개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20249738오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/202410814오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/202412165개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...