Which is better? cast nullable type or retrieve the value with Value property?

Is there a performance benefit to one way over the other?

No. They both compile to the exact same IL. The cast is syntactic sugar for the Value property. This code:

int? x = null;
Console.WriteLine(x.Value);
Console.WriteLine((int)x);

compiles to these IL instructions, ignoring nops: (you can test this yourself using ildasm, ILSpy, DotPeek, etc.)

// int? x = null;
ldloca.s 0
initobj valuetype [mscorlib]System.Nullable`1<int32>

// Console.WriteLine(x.Value);
ldloca.s 0
call instance !!0 [mscorlib]System.Nullable`1<int32>::get_Value()
call void [mscorlib]System.Console::WriteLine(int32)

// Console.WriteLine((int)x);
ldloca.s 0
call instance !!0 [mscorlib]System.Nullable`1<int32>::get_Value()
call void [mscorlib]System.Console::WriteLine(int32)

Are there other reasons to choose one over the other?

I prefer to avoid casts when I can, because there’s always the potential for them to get out of sync with the actual type. If I change my variable from int? to byte?, then all my casts are wrong — but if I was using .Value, I’m free to change the variable as necessary. To me, the hard cast doesn’t add anything in terms of readability, but it does cost in terms of maintainability.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)