일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- csharp
- convert
- Visual Studio
- mysql
- WPF
- string
- IValueConverter
- algorithm
- dotNET
- git
- Github
- ListView
- Microsoft
- logging
- programmers
- Process
- C#
- nullable
- log
- commit
- tls
- windows
- Binding
- File
- .net
- coding-test
- 코딩테스트
- windows10
- Coding
- chashtag
Archives
- Today
- Total
CHashtag
[C#] Extension Method 요청인자가 null일 때 NullReferenceException이 발생하지 않는 이유 본문
C#
[C#] Extension Method 요청인자가 null일 때 NullReferenceException이 발생하지 않는 이유
HyoSeong 2023. 1. 17. 22:07반응형
아래 코드를 보다 불현듯 이런 생각이 스쳤다.
public static class Extensions
{
public static string TestExtension(this string value)
{
return value + "Hi";
}
}
public class Program
{
public void Main(string[] args)
{
string a = null;
var b = a.TestExtension();
}
}
보통 null에 대한 method를 호출할 때 NullReferenceException(이하 NRE)이 발생하지 않나? 라는 생각이.
그러나 Extension Method에서는 NRE가 발생하지 않는다!
그 이유는, Extension Method가 il코드로 변환될 때 callvirt가 아닌 call 로 변환된다고 한다.
그냥 이렇게 이해하면 편할듯하다. (이해를 돕기위한 개인적인 의견입니다.)
Extension Method는 내부적으로 Static Method를 호출하는것과 같다.
Extensions.TestExtension(null); 을 호출한다고 NRE가 발생하진 않지 않는가!
In C#, what happens when you call an extension method on a null object?
Does the method get called with a null value or does it give a null reference exception? MyObject myObject = null; myObject.MyExtensionMethod(); // <-- is this a null reference exception? If t...
stackoverflow.com
반응형
'C#' 카테고리의 다른 글
[C#] bigint란 무엇이며, bigint는 무한한 값을 저장할 수 있을까? (1) | 2023.02.20 |
---|---|
[C#] 숫자 천단위 콤마찍기 (금액 표기하기) (0) | 2023.01.24 |
[C#] SendKeys.Send() ArgumentException 문자열이 잘못되었습니다. 해결방법 (0) | 2022.11.30 |
[C#] IE기반 WebBrowser는 지원 중단되나? (0) | 2022.08.28 |
[C#] Guid 사용방법 (생성, 비교, ToString()) (0) | 2022.04.05 |