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?
+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 theValue
nor 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
2010-10-20 20:52:04
@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
2010-10-20 20:55:33
@Anthony I just highlighted the code block and hit the "code" button. Not sure what happened there.
David Lively
2010-10-20 21:13:43
It's fine, probably some sort of merging issue; I was in the middle of editing it. No offence taken anyway. Cheers.
Ani
2010-10-20 21:16:47
@David, ah. Well. Now we see why the world is shaped like a banana.
Anthony Pegram
2010-10-20 21:20:05
+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
2010-10-20 20:57:13