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
반응형