In C#, what happens when you call an extension met

2019-01-04 17:48发布

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 this is the case I will never need to check my 'this' parameter for null?

7条回答
啃猪蹄的小仙女
2楼-- · 2019-01-04 18:17

A null will be passed to the extension method.

If the method tries to access the object without checking is it null, then yes, it will throw an exception.

A guy here wrote "IsNull" and "IsNotNull" extension methods that check is the reference passed null or not. Personally I think this is an aberration and shouldn't have seen light of day, but it's perfectly valid c#.

查看更多
登录 后发表回答