tags:

views:

52

answers:

2

I'm sure this has been asked before, but my perusal of the search hits for similar questions did not yield an answer.

I am tired of checking if Nullable has a value. Why can't I assign myNullable<int> yourAge to int myAge and get an exception if yourAge is null? Furthermore, if either of our damned ages is null, why do I have to do a fxning check to avoid assigning 'deafault' to a fxning SqlParameter? I can't even do a civilised mySqlParm = myAge.HasValue ? myAge.Value : DBNull.Value.

What is the fxning point of nullable types? We still have to use `-1' for a pkId to avoid the dreaded Null. We can't even add our own extension menthods because 'blah blah'.

Why even fxning bother with parameters at all? Why don't we just store all dates as fxning varchar(10)?

+6  A: 

Why can't I assign myNullable<int> yourAge to int myAge and get an exception if yourAge is null?

Of course you can. Just use the Value property without checking first:

int myAge = yourAge.Value;

If yourAge contains null you will get an exception.

Guffa
Thanks @Guffa, never occurred to me, being blinded by other complexities.
ProfK
+3  A: 

Maybe you want to do something like this?

public static object GetDatabaseValueFromNullableType<T>(this T? value) 
    where T: struct
{
    return value.HasValue ? (object) value.Value : DBNull.Value;
}

and then you can use it like so:

//this is just a test I wrote but you get the idea
[Test]
public void NullableTest()
{
    int? something = null;
    var value = something.GetDatabaseValueFromNullableType();
    Assert.IsTrue(value == DBNull.Value);
}
Joseph
+1 for the test based example. You deserve a bounty, but I can only do that on my next question. Stay tuned. :-)
ProfK