Wednesday, October 20, 2010

Nullable Value vs Casting.

Was talking to a team member half an hour ago, and he pointed out that he needs to change a line of code like this code (isLocked is a nullable bool)
bool isEnabled = (bool)isLocked


bool isEnabled = isLocked.Value

I asked him why you need to do it that way….and his answer was NO IDEA…
So thought of dissembling the IL to see what was really happening. This is the dissembled code I got from Reflector..

public struct Nullable where T: struct


private bool hasValue;

internal T value;

public Nullable(T value) { this.value = value; this.hasValue = true; }
public bool HasValue { get { return this.hasValue; } }

public T Value { get { if (!this.HasValue) }

ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue); return this.value; }
public T GetValueOrDefault() { return this.value; }

Digging it a little bit more, doing a casting on a nullable generates IL the same as when you use .Value property, so there is no difference in casting a nullable type or using the .Value property.

But interesting to note from the dissembled code is that using the method GetValueOrdefault() on a nullable type is more efficient then using Value, as the check .HasValue does not happen, i.e you would prefer Value over GetValueOrDefault() if you just want to get the default value when the type does not have a value.

No comments:

Post a Comment