[2.0] nullable modifier??
I want to basically retrieve a value in a database table and assign it to a variable.
I declared the variable as nullable (basically I can assign a null value to the variable)
But it doesn't work. if the retrieved value has a null value I am not able to assign to the variable with nullable modifier. I get run time error saying "invalid cast" in the second line of the code.
while (oDataReader.Read())
{
double? dAdvRateNullableType = (double)oDataReader[0];
if (dAdvRateNullableType.HasValue == true)
{
Console.WriteLine("there is value in the field and the value is " + (double)oDataReader[0]);
}
else
{
Console.WriteLine("there is no value in the field");
}
}
1 Attachment(s)
Re: [2.0] nullable modifier??
A null database field actually contains an object, specifically DBNull.Value. That is not the same as C#'s null. Also, you're casting the field as double, so even if it did contain null your variable wouldn't get it because the cast would make it zero. You should use something like:
Code:
double? dAdvRateNullableType = oDataReader[0] is DBnull ? null : (double)oDataReader[0];
Re: [2.0] nullable modifier??
Re: [2.0] nullable modifier??
Actually, there's a better way. I didn't think you could do this because Double is a value type but with double? it works:
Code:
double? dAdvRateNullableType = oDataReader[0] as double?;
The 'as' operator attempts to cast the object as the specified type and returns null if it fails. That means that if the field is DBNull.Value it cannot be cast as Double so the expression returns null, which is exactly what you want.
Re: [2.0] nullable modifier??
awesome Jm.
thanks a million.
nath