.NET Internals Cookbook Part 3 — Initialization tricks

This is the third part of the .NET Internals Cookbook series. For your convenience you can find other parts in the table of contents in Part 0 – Table of contents

13. Can a variable be true and false at the same time?

Yes, see this

Output:

The output is very misleading and that is because of operator rules.

We have a short circuiting in C#. This means that when we use logical conjunction (and) and first argument is false then second one is not evaluated. For logical disjunction (or) it happens when first argument is true.

To have the short circuiting in conjunction with custom operators we check whether the first argument is false. So we call foo.false() here and based on that return value or carry on. In this sample we conclude that foo is false (because the method returned true) so we want to “cast” it to boolean value (because this is what if condition requires). So we call foo.true(). And then we enter the if block.

Decompiled code looks like this:

14. Can you create an object without invoking its constructor?

Yes, like this:

Output:

This is useful when implementing some deserialization as we may want to initialize properties manually instead of invoking the constructor.

15. Can you invoke object’s constructor multiple times?

Yes, by using reflection. See this code:

Output (no surprise):

You can also generate some IL code doing that.

16. Can you return null from a constructor?

Yes, try this:

It gets even more interesting if you try it here — it runs custom constructor but the reference is still non-null. I tried it with VS and get the expected result, can’t explain what is happening in tio.

17. Can you create an instance of an interface?

Yes, see this code:

Wow, magic. We not only create instance of an interface but also pass some constructor arguments! When you decompile the code you can see that actually under the hood you have this:

So we just create an instance of Foo class. This is because we actually create a COM object under the hood.