Microsoft MVP성태의 닷넷 이야기
닷넷: 2344. C#의 Identity conversion 의미 [링크 복사], [링크+제목 복사],
조회: 78
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13470정성태12/2/202313446닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입 [1]파일 다운로드1
13469정성태12/1/202313539닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/202312337닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/202313452오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/202312289닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/202312722개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/202312476닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/202311116오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/202312195오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/202312184닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/202312444닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/202313209닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/202313454닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/202312674VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/202313760닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/202313312닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/202313697닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/202311092오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/202312201닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/202312248닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/202312259닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/202312720개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/202311668닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/202312688닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/202313288닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/202314317Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...