Thursday, November 24, 2011

callvirt

The first release of the .NET Framework was about 10 years ago (13 February 2002). How well do you know the framework? Take a look at the following class:

(click to enlarge)

Simple. A static field, a static method and an instance method. Both methods return the static field. Now, imagine that we have the following in main:

(click to enlarge)

As you probably noticed, there's an instance call using a null reference. So, the first idea that pops up in your head when someone asks "Will this code throw an exception?" is "Yes, it will! A NullReference exception to be exact". Well, if we compile it and run it using Visual Studio, it will actually throw an exception:

(click to enlarge)

So, what's the catch? Well, the right answer to the question above is "It depends". If we look at the generated IL, we can see that the compiler emmited the "callvirt" instruction for the instance method:

(click to enlarge)

That's the normal behaviour. The C# compiler emmits a callvirt instruction on every instance method. It does so in order to check for an object reference at runtime (TypeSafety). But, if we write the exact same code in IL and replace the callvirt by a call instruction and compile it using ILASM:

(click to enlarge)

It works:

(click to enlarge)

This is because the instance method is only using a static field and, at that point of the code, the type constructor already did it's work and the method works fine. If you look at both the assemblies ("C# Compiled" and "ILASM compiled") in .NET Reflector, both generate the following C# code (Main):

(click to enlarge)

If you ever get the change to read this, thanks MC.

Thursday, September 8, 2011

Everything is volatile (.NET Micro)

If you ever builted multithreaded applications, you most certainly came across the volatile keyword. As stated on MSDN, "The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times". Just recently, I needed this "volatile behaviour" in a .NET MicroFramework project. But when using the keyword "volatile" the compiler actually yielded an error:

(click to enlarge)

What? IsVolatile is not defined? After googling a little I ended up on a blogpost from de .NET Micro development team. Turns out that everything is treated as volatile in the .NET MicroFramework. Well, it makes sense...

Monday, September 5, 2011

Block Scope

From time to time, coworkers come to me asking for help. Whenever I have the time, I'm glad to help out. The last help request was actually quite interesting. Here it goes:

Take a look at the following C# code:

(click to enlarge)

In the above code, we're using the "i" variable from the loop in an anonymous method. Later on, we print the result of the method execution. Now, what do you expect to get printed in the console? At a glance, some would say " 0 1 2 3 4 5 6 7 8 9 ", since we're iterating from 0 to 10 (excluded). But no. What actually comes out is a sequence of the integer "10":

(click to enlarge)

What? Why? Well, since the "i" variable is used in an anonymous method that does not get executed in the first "for" loop, the "i" variable will actually have the last value stored (10 because "i" gets incremented one last time to be evaluated in the loop condition). The "i" variable is not evaluated until we actually execute the anonymous method. So, how to solve this? Well, since C# has the notion of "block scope", we can actually declare a variable inside the "for" loop and it will be evaluated and "captured" in the anonymous function:

(click to enlarge)

And the output is now what we want:

(click to enlarge)

This kind of problem is very common when developing multithreaded applications. Which thread captures what, volatile and so on.

Now, in C# that was trivial. Let's look at a Javascript example that replicates this problem:

(click to enlarge)

As you can see, we're dynamically attaching a function to the onclick event of 10 buttons. The function attached will just show an alert with a sequential number. But just like in the C# example, we won't get a sequence of 0 to 9 alerts. Every click on every button will alert a "10" integer.

(click to enlarge)

This is where it gets tricky. Since JavaScript doesn't have the notion of "block scope", doing the same as we did in C# won't yield the expected result:

(click to enlarge)

This will alert "nines" ("9" because now the temporary variable won't be incremented one last time for the condition evaluation).

(click to enlarge)

To work around this issue, you can "simulate" the block scope by defining "inline functions" and executing them on the fly:

(click to enlarge)

In the above code, we define a function and execute it immediately, "capturing" the value of the "i" variable into another variable. This means that the "i" was evaluated when passed to the alert method that was set to the onclick event.

(click to enlarge)

Simple uh?