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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...
NoWriterDateCnt.TitleFile(s)
12893정성태12/27/202119937.NET Framework: 1124. C# - .NET Platform Extension의 ObjectPool<T> 사용법 소개파일 다운로드1
12892정성태12/26/202115771기타: 83. unsigned 형의 이전 값이 최댓값을 넘어 0을 지난 경우, 값의 차이를 계산하는 방법
12891정성태12/23/202117529스크립트: 38. 파이썬 - uwsgi의 --master 옵션
12890정성태12/23/202117278VC++: 152. Golang - (문자가 아닌) 바이트 위치를 반환하는 strings.IndexRune 함수
12889정성태12/22/202119381.NET Framework: 1123. C# - (SharpDX + DXGI) 화면 캡처한 이미지를 빠르게 JPG로 변환하는 방법파일 다운로드1
12888정성태12/21/202116476.NET Framework: 1122. C# - ImageCodecInfo 사용 시 System.Drawing.Image와 System.Drawing.Bitmap에 따른 Save 성능 차이파일 다운로드1
12887정성태12/21/202121311오류 유형: 777. OpenCVSharp4를 사용한 프로그램 실행 시 "The type initializer for 'OpenCvSharp.Internal.NativeMethods' threw an exception." 예외 발생
12886정성태12/20/202116239스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/202118437오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/202117461개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/202116845오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/202117177개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/202116185개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/202117798VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202124343오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
12878정성태12/15/202117445개발 환경 구성: 617. 윈도우 WSL 환경에서 같은 종류의 리눅스를 다중으로 설치하는 방법
12877정성태12/15/202117895스크립트: 36. 파이썬 - pymysql 기본 예제 코드
12876정성태12/14/202117895개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/202116035스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/202115291오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/202117699오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/202117506개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
12871정성태12/12/202116397오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/202116211개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/202118814개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/202117502오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...