MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

cast Nullable to ValueType

Is there any difference between Nullable.Value and (<whatEverType>) Nullable? As far as I know both methods return NULL if the value is not set or the value itself.

e.g:

DateTime? date = DateTime.Now;
DateTime now = (DateTime) date;
DateTime now2 = date.Value;

Upvotes: 1

Views: 176

Answers (1)

user2160375
user2160375

Reputation:

Nope, there is no difference. You will get InvalidOperationException in both cases when value is not set. What is more, here is implementation of the cast operator inside Nullable<T>:

public static explicit operator T(Nullable<T> value) {
    return value.Value;
}

(decompiled with Resharper)

So the cast operator uses the Value member.

Upvotes: 7

Related Questions