this == null inside .NET instance method - why is that possible?

后端 未结 5 853
别那么骄傲
别那么骄傲 2020-12-14 15:22

I\'ve always thought that it\'s impossible for this to be null inside instance method body. Following simple program demonstrates that it is possible. Is this s

5条回答
  •  爱一瞬间的悲伤
    2020-12-14 15:46

    this is a reference, so there is no problem with its being null from the perspective of the type system.

    You may ask why NullReferenceException was not thrown. The full list of circumstances when CLR throws that exception is documented. Your case is not listed. Yes, it is a callvirt, but to Delegate.Invoke (see here) rather than to Bar, and so the this reference is actually your non-null delegate!

    The behavior you see has an interesting implementational consequence for CLR. A delegate has a Target property (corresponds to your this reference) that is quite frequently null, namely when the delegate is static (imagine Bar be static). Now there is, naturally, a private backing field for the property, called _target. Does _target contain a null for a static delegate? No it doesn't. It contains a reference to the delegate itself. Why not null? Because a null is a legitimate target of a delegate as your example shows and CLR does not have two flavors of a null pointer to distinguish the static delegate somehow.

    This bit of trivium demonstrates that with delegates, null targets of instance methods are no afterthought. You may still be asking the ultimate question: but why they had to be supported?

    The early CLR had an ambitious plan of becoming, among others, the platform of choice even for sworn C++ developers, a goal that was approached first with Managed C++ and then with C++/CLI. Some too challenging language features were omitten, but there was nothing really challenging about supporting instance methods executing without an instance, which is perfectly normal in C++. Including delegate support.

    The ultimate answer therefore is: because C# and CLR are two different worlds.

    More good reading and even better reading to show the design allowing null instances shows its traces even in very natural C# syntactic contexts.

提交回复
热议问题