A while back I compiled two versions of the code using (Nullable<T>)x.GetValueOrDefault(y) and one using (Nullable<T>)x ?? y) (Nullable<T>)x ?? y) .
After decompiling in IL, I noticed that the null coalesce statement is converted to a GetValueOrDefault call.
Since this is a method call to which you can pass an expression that evaluates before the method executes, y seems to always be executed.
For example:
using System; public static class TestClass { private class SomeDisposable : IDisposable { public SomeDisposable() {
It seems like this leads to an underdeveloped object and probably to performance consequences.
First of all, is it true? Or does JIT or something similar modify the actually executed ASM code?
And secondly, can anyone explain why he has such behavior?
NOTE: This is just an example, it is not based on real code and please refrain from comments such as "this is bad code."
IL DASM:
Well, when I compiled this with the .Net Framework 2.0, it led to identical code calling null coalesce and GetValueOrDefault. With .Net Framework 4.0, it generates these two codes:
GetValueOrDefault:
.method private hidebysig static void Main() cil managed { .entrypoint
Null Coalesce:
.method private hidebysig static void Main() cil managed { .entrypoint
As it turns out, this is no longer the case, and that it misses the GetValueOrDefault call in general when HasValue returns false.
c # nullable
Aidiakapi
source share