Tom
Tom

Reputation: 2254

Visual Studio 2012 not recognising nullable type

I have 2 nullable DateTimes, so subtracting them will result in a nullable TimeSpan. I want to call .Value on this.

However, the autocompletion drop-down list thinks that the type inside the brackets is a normal TimeSpan. .Value is not in the list, and when I use any of the suggestions, it doesn't compile. It does compile when I manually type .Value.

The same issue occurs if only one of the DateTimes are nullable. It also occurs if I add a TimeSpan? to a DateTime? resulting in a DateTime?. Intellisense thinks it is a DateTime.

Is this a problem with Visual Studio's intellisense? I am at update 3, I do not have ReSharper. Same issue on another computer.

Edit: to be clear, I am asking a question about why intellisense is suggesting the wrong type. I know what to write to make the code compile.

Upvotes: 6

Views: 308

Answers (1)

Hans Passant
Hans Passant

Reputation: 942255

Agreed, IS gets this wrong and doesn't correctly infer that the result of the subtraction is a Nullable<TimeSpan>, it infers TimeSpan. You can whack it over the head by writing it like this instead:

var span = date1 - date2;
span.

Now is does correctly infer the type of the span variable, you'll see HasValue in the auto-completion window. This otherwise isn't slower at all at runtime so its a reasonable workaround.

Nothing you or we can do about the original oops, you can however file a feedback report at connect.microsoft.com. Post a link so we can vote for it.

Upvotes: 5

Related Questions