T
tshad
I have a function that is being passed as an object but is really a string
so that I can handle DBNull.Value.
You cannot pass a DBNull.Value to a string parameter but you can pass a null
value. Not sure why this is but if I have the following:
private static void SetAddressFields(Address adress, object zip)
where Address is class which has a string property of zip (address.Zip).
In the routing I have the following code:
if (zip != DBNull.Value)
address.Zip = (string)zip;
else
address.FieldToNull("Zip");
Where address.FieldToNull handles null entries.
What is confusing is that if I do:
SetAddressFields(address, dr["Zip"]);
And dr["Zip"] is equal to DBNull.Zip,
my test works: if (zip != DBNull.Value).
If I call the same function where I pass a null where zip is equal to null:
SetAddressFields(address, zip)
or
SetAddressFields(address, null);
Both of these pass back a false from the DBNull.Value test because null is
not DBNull.Value test.
But the code still works.
You can set a string to null, but not to DBNull.Value.
I thought that I would have to change the code to:
if (zip != DBNull.Value && zip != null)
To handle both situations but since you can set a string to null, you only
have to handle the DBNull situation.
Is there another way to handle both situations?
Thanks,
Tom
so that I can handle DBNull.Value.
You cannot pass a DBNull.Value to a string parameter but you can pass a null
value. Not sure why this is but if I have the following:
private static void SetAddressFields(Address adress, object zip)
where Address is class which has a string property of zip (address.Zip).
In the routing I have the following code:
if (zip != DBNull.Value)
address.Zip = (string)zip;
else
address.FieldToNull("Zip");
Where address.FieldToNull handles null entries.
What is confusing is that if I do:
SetAddressFields(address, dr["Zip"]);
And dr["Zip"] is equal to DBNull.Zip,
my test works: if (zip != DBNull.Value).
If I call the same function where I pass a null where zip is equal to null:
SetAddressFields(address, zip)
or
SetAddressFields(address, null);
Both of these pass back a false from the DBNull.Value test because null is
not DBNull.Value test.
But the code still works.
You can set a string to null, but not to DBNull.Value.
I thought that I would have to change the code to:
if (zip != DBNull.Value && zip != null)
To handle both situations but since you can set a string to null, you only
have to handle the DBNull situation.
Is there another way to handle both situations?
Thanks,
Tom