Microsoft MVP성태의 닷넷 이야기
닷넷: 2344. C#의 Identity conversion 의미 [링크 복사], [링크+제목 복사],
조회: 32
글쓴 사람
정성태 (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)
13973정성태7/21/202531닷넷: 2345. C# - 배열 및 Span의 공변성파일 다운로드1
13972정성태7/21/202532닷넷: 2344. C#의 Identity conversion 의미파일 다운로드1
13971정성태7/17/2025693닷넷: 2343. C# 14 - (2) 속성 구문에서 문맥 키워드로 추가되는 field 예약어파일 다운로드1
13970정성태7/17/2025744닷넷: 2342. C# 14 - (1) (예약)
13969정성태7/17/2025702닷넷: 2341. snap으로 설치한 .NET 리눅스 실행 환경
13968정성태7/16/2025707오류 유형: 969. lddtree - TypeError: 'type' object is not subscriptable
13967정성태7/16/20251054오류 유형: 968. snap으로 설치한 "dotnet run" 실행 시 "undefined symbol: _dl_audit_symbind_alt, version GLIBC_PRIVATE" 오류
13966정성태7/15/20251501디버깅 기술: 223. WinDbg - .kframes 명령어
13965정성태7/11/20251387오류 유형: 967. 디버깅 모드로 실행 시 "Could not find file 'C:\Program Files\IIS Express\Oracle.DataAccess.Common.Configuration.Section.xsd'" 예외
13964정성태7/10/20251878닷넷: 2340. C# - Win32 Multimedia Timer 주기파일 다운로드1
13963정성태7/8/20251588VS.NET IDE: 202. Visual Studio 2022 + Copilot 기본 사용법
13962정성태7/7/20251658스크립트: 79. 파이썬 - onnxruntime_genai에서 지원하지 않는 모델 사용
13961정성태7/5/20251430디버깅 기술: 222. WinDbg 분석 사례 - IISreset 시점에 w3wp.exe의 crash 발생
13960정성태7/3/20252467개발 환경 구성: 752. ProcDump - C/C++ 예외 코드 필터를 지정한 덤프 생성 [2]
13959정성태6/25/20251576오류 유형: 966. Ubuntu - ping: connect: Network is unreachable
13958정성태6/21/20252130닷넷: 2339. C# - Phi-4-multimodal 모델의 GPU 가속 방법 (ORT 사용)파일 다운로드1
13957정성태6/20/20252535닷넷: 2338. C# / Foundry Local - Phi-4-multimodal 모델을 사용하는 방법 [1]
13956정성태6/19/20251914개발 환경 구성: 751. Triton Inference Server의 Python Backend 프로세스
13955정성태6/18/20252048오류 유형: 965. Hugging Face 모델 다운로드 시 "requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: ..." 오류
13954정성태6/18/20251937닷넷: 2337. C# - Hugging Face에 공개된 LLM 모델을 Foundry Local에서 사용하는 방법파일 다운로드1
13953정성태6/16/20251725스크립트: 78. 파이썬 - 소스 코드의 파일 경로를 지정한 모듈 로드
13952정성태6/15/20252219닷넷: 2336. C# - IValueTaskSource로 인해 주의가 필요한 ValueTask 호출파일 다운로드1
13951정성태6/15/20252052오류 유형: 964. Outlook - 일정이 "You cannot make changes to contents of this read-only folder." 오류 메시지로 삭제가 안 되는 경우
13950정성태6/12/20252750닷넷: 2335. C# - 간단하게 구현해 보는 IValueTaskSource 예제파일 다운로드1
13949정성태6/11/20252681오류 유형: 963. SignTool - "Error: SignerSign() failed." (-2146869243/0x80096005)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...