C# ?? null coalescing operator - c#

I have defined Class Person property Birthday as nullable DateTime? , so why shouldn’t the null coalescing operator work in the following example?
cmd.Parameters.Add(new SqlParameter("#Birthday",
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? DBNull.Value;
The compiler err I got was "Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'"
The following also got a compile error :
cmd.Parameters.Add(new SqlParameter("#Birthday",
SqlDbType.SmallDateTime)).Value =
(person.Birthday == null) ? person.Birthday:DBNull.Value;
I added a cast to (object) as recommended by Refactor, and it compiled, but didn’t work properly and the value was stored in the sqlserver db as null in both cases.
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? (object)DBNull.Value;
Can someone explain what is going on here?
I needed to use the following clumsy code:
if (person.Birthday == null)
cmd.Parameters.Add("#Birthday", SqlDbType.SmallDateTime).Value
= DBNull.Value;
else cmd.Parameters.Add("#Birthday", SqlDbType.SmallDateTime).Value =
person.Birthday;

The problem is that DateTime? and DBNull.Value are not the same type so you can't use the null coalescing operator on them.
In your case you can do person.Birthday ?? (object)DBNull.Value to pass a value of type object through to Add()

I prefer to iterate over my parameters just before executing the query, changing all instances of null to DBNull as appropriate, for example:
foreach (IDataParameter param in cmd.Parameters)
if (param.Value == null)
param.Value = DBNull.Value;
This lets me leave null values as-is and simply swap them out en masse later.

Your first problem is that for the ?? or ?: operator, the objects for either choice must be the same type. Here they are different type.

Related

null to DBNull in AddWithValue using object variable in C#

I am trying to make the optional parameter of a C# Method to be converted to DBNull (if it is null) to be added with Parameter.AddWithValue method.
I saw many solutions (Set a database value to null with a SqlCommand + parameters), extension methods, etc, but i wanted a single line solution.
command.Parameters.AddWithValue("#Municipio", municipio ?? DBNull.Value)don't work (Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull')
The method: public static void Foo(string bar, string municipio = null)
Unfortunately i can't do string municipio = DBNull.Value because "default parameter must be a compile-time constant" (what i don't exactly understand the meaning).
I was able to make it work as such:
object obj = municipio == null ? command.Parameters.AddWithValue("#Municipio", DBNull.Value) : command.Parameters.AddWithValue("#Municipio", municipio);
I am very uncomfortable with this, seems like a JavaScript way of doing, i want something like:
if municipio == null ? command.Parameters.AddWithValue("#Municipio", DBNull.Value) : command.Parameters.AddWithValue("#Municipio", municipio);
But somehow i am not being able to make it work like this, perhaps im missing some syntax (i tried many parenthesis/etc combinations).
So my question is, is it good practice the one-line solution i reached, or should i replace it?
Updated to handle if the variable is not initialized.
Here is an example:
OracleParameter P_COUNTYCODE = new OracleParameter("P_COUNTYCODE", OracleDbType.Varchar2);
P_COUNTYCODE.Direction = ParameterDirection.Input;
P_COUNTYCODE.Value = countyCode.Length > 0 ? countyCode : (object)DBNull.Value;
try:
command.Parameters.AddWithValue("#Municipio", !string.IsNullOrEmpty(municipio) > 0 ? municipio : (object)DBNull.Value)

How to return a null value from a database

I am trying to populate a combobox with a list my query returns. When I execute my program it gives me a specified cast is not valid error ( I have it execute on page load event). Every field in the database I have to work with can be null except the primary key. So I tried using DBNull.Value but it can't get my (int)reader fields to work. I have supplied my code below for a better understanding. How can I get my (int)reader's to work with my statements, so they can read when there is a null value?
CustData cd = new CustData();
cd.CustomerID = (int)reader["CustomerID"];
cd.Name = reader["Name"] != DBNull.Value ? reader["Name"].ToString() : string.Empty;
cd.ShippingAddress = reader["ShippingAddress"] != DBNull.Value ? reader["ShippingAddress"].ToString() : string.Empty;
cd.ShippingCity = reader["ShippingCity"] != DBNull.Value ? reader["ShippingCity"].ToString() : string.Empty;
cd.ShippingState = reader["ShippingState"] != DBNull.Value ? reader["ShippingState"].ToString() : string.Empty;
cd.ShippingZip = (int)reader["ShippingZip"];
cd.BillingAddress = reader["BillingAddress"] != DBNull.Value ? reader["BillingAddress"].ToString() : string.Empty;
cd.BillingCity = reader["BillingCity"] != DBNull.Value ? reader["BillingCity"].ToString() : string.Empty;
cd.BillingState = reader["BillingState"] != DBNull.Value ? reader["BillingState"].ToString() : string.Empty;
cd.BillingZip = (int)reader["BillingZip"];
cd.Territory = reader["Territory"] != DBNull.Value ? reader["Territory"].ToString() : string.Empty;
cd.Category = reader["Category"] != DBNull.Value ? reader["Category"].ToString() : string.Emptyy
That is because int is not nullable. You need to use int? or nullable<int> (long hand) to allow it to be an int OR a null value.
You can then use the usual .HasValue and .Value etc to get the value from the item.
EDIT: To enhance the visibility of my comment to this answer. I would advise against checking for NULL and storing Zero into your property because then when you save back you are changing a Null to a Zero even though nothing has been changed by the system. Now, reports etc may distinguish between NULL and Zero (very often) and could start doing strange things!
Null does NOT equal zero!! If you assume it does as a work around... What happens if I truly do want to record zero? How do you differentiate between a real zero and a "was null now zero" trick? Do it right, save yourself the pain!
Use nullable int, or just make your control for your int's too
reader["ShippingZip"] != DBNull.Value ? (int)reader["ShippingZip"] : default(int);
You should use a nullable int for your variable and cast it, like (int?). Int can only have a value; nullable types can also be null. When you use a nullable type, you can look at the property .HasValue. Here is the MSDN page: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

Why I can't to this assignment?

This is my code:
DateTime? test;
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null));
Why can I not set that variable to null?
Aside from anything to do with Nullable<T> (in this case, DateTime?), the error is happening specifically here:
((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday : null))
Note that there's no mention of a nullable DateTime in this code. And before the result of this code is assigned to a nullable DateTime, this code by itself needs to be evaluated. It can't be, because of the error you're seeing.
The operator being used (: ?) needs to be able to infer types from all arguments to the operation, and those types need to be able to match. Here you're passing it a DateTime and null which can't be matched. Try casting one of the arguments:
((objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday : null))
You can't set null in this case because ternary operator must return values same types
try this:
test = (objectParsed.birthday != null) ? (DateTime?)DateTime.Parse((string)objectParsed.birthday): null;
Try with
test = ((objectParsed.birthday != null) ? DateTime.Parse((string)objectParsed.birthday): null;
Explanation: the structure of a ternary operator is:
variable = (condition)?(value if yes):(value if no);

?? operator didn't trigger System.DBNull type in DataTable DataRow

This is a follow-up question to .Net C# String.Join how to output “null” instead of empty string if element value is null? where the answer suggested to use the ?? operator to define a custom null value, but the replacement never got triggered.
DataSet myDataSet = new DataSet();
mySqlDataAdapter.Fill(myDataSet);
DataTable rotationData = myDataSet.Tables["Table"];
rotationValues = string.Join(", ",
from r in rotationData.Rows.OfType<DataRow>()
select r[5] ?? "null");
When I change the code to:
rotationValues = string.Join(", ",
from r in rotationData.Rows.OfType<DataRow>()
select r[5].GetType());
I can observe that the data type for elements that have valid data in them is System.Double whereas the data type for elements which are NULL is System.DBNull. Does ?? not operate on System.DBNull?
No DBNull and null is not the same thing.
But you can write this instead:
select r[5] == DBNull.Value ? "null" : r[5]);
Another possibility is to use Field extension method, it will give you strongly-typed access to each of the column values in the specified row, and the ?? operator will work.
select r.Field<string>(5) ?? "null";
?? operates on the programming language null, not on the database DBNull.
From MSDN:
Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.

Why ?: operator does not work with nullable<int> assignation?

I'm creating an object for my database and I found a weird thing, which I don't understand:
I've an object which should reference a "language" by an ID, but this can be null, so my property is a int?(Nullable<int>)
so firstly I tried to use the object initializer:
myObject = new MyObject()
{
myNullableProperty = language == null ? null : language.id;
}
but it doesn't work! It tell me that null cannot be converted to int
But if I it in a if/else structure, I can put null in a var and then assign it to my properties.
Why is this acting like this?
You may try casting the null to int? as the ?: operator requires both operands to return the same type:
myNullableProperty = language == null ? (int?)null : language.id
This is because of a type mismatch. You must cast your null value to the int type.
The reason is, when using the ? operator the left and the right side of the : are required to be from the same type and typeof(null)!=typeof(int) so:
myNullableProperty = language == null ? (int?)null : language.id;
Most likely null is interpreted as object which obviously can't be assigned to int. You might want to use myNullableProperty = language == null ? (int?)null : language.id;

Categories

Resources