views:

94

answers:

4

i have an existing DateTime? object that has a datetime in it. I want to remove the datetime value from it so when you ask "HasValue" it returns false?

+5  A: 

Set it to null.

John Saunders
+6  A: 

Nullable<T>is immutable, so you will have to reassign the variable to a different value to be able to change / remove the underlying value. This makes sense since it is a value-type (although a special one at that); value-types are normally immutable in the framework. You will notice that neither theValuenor theHasValue property forNullable<T>has a setter.

DateTime? nullableDt = DateTime.Now; 
Console.WriteLine(nullableDt.HasValue); //true

nullableDt = null; 
Console.WriteLine(nullableDt.HasValue); //false

or

nullableDt = new DateTime?();
Ani
@David, post a comment before (or instead of) changing someone's wording? Particularly on a fresh answer. Don't take the wiki thing too far. If you have an issue with someone's phrasing, mention it, give them a chance to fix it or explain it.
Anthony Pegram
@Anthony I just highlighted the code block and hit the "code" button. Not sure what happened there.
David Lively
It's fine, probably some sort of merging issue; I was in the middle of editing it. No offence taken anyway. Cheers.
Ani
@David, ah. Well. Now we see why the world is shaped like a banana.
Anthony Pegram
+3  A: 

If you have

DateTime? value = DateTime.Now;

then call

value = null;
Brad
+1  A: 

Why not just set it back to null?

  DateTime? d = null;

  System.Diagnostics.Debug.WriteLine("HasValue1 = {0}", d.HasValue); //False

  d = DateTime.Now;

  System.Diagnostics.Debug.WriteLine("HasValue2 = {0}", d.HasValue); //True

  d = null;

  System.Diagnostics.Debug.WriteLine("HasValue3 = {0}", d.HasValue); //False
wageoghe