Michal Strehovský Profile picture
Moved to Bluesky - https://t.co/Y20BvEBfjl. The account also bridges to Mastodon at @migeel.sk@bsky.brid.gy

Oct 13, 2019, 5 tweets

1/5 A little know C#/.NET fact is that one can end up in a situation where `this is null` evaluates to true. One just needs a bit of reflection.

2/5 There's good reasons why it's little known. For one, it's kind of useless. The other reason is that doing that starts breaking invariants. For example, C# assumes `this` is always non-null. Call to `this.AndAgain()` should throw, but it won't.

3/5 It also breaks invariants within the runtime. This snippet will work as expected, no surprises:

4/5 But this one will hit a `NullReferenceException` in a spot that the debugger cannot figure out. It has to do with how generic code over reference types gets shared within the runtime.

5/5 .NET Native has an optimization that eliminates the entire method bodies on types that were never seen as allocated that also doesn't play well with this. This makes a good party trick (if the parties you go to are like the parties I go to), but don't do this in real code

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling