I have an Oracle data table fetching columns that be null. So I figure to keep the code nice and simple that I'd use the ?? operand. AlternatePhoneNumber is a string in my C# model.
AlternatePhoneNumber = customer.AlternatePhoneNumber ?? ""
However, even with that code I still get the error.
System.InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.String'.
I know what the error means but why is ?? not usable on DBNull? Isn't null and DBNull essentially the same?
Thank you.
The ?? operator only applies to actual nulls.
null and DBNull.Value are not the same; DBNull.Value is simply a placeholder object.
Also, that exception is coming from inside the AlternatePhoneNumber property, before your ?? operator executes. (Your code doesn't have a cast).
If customer is a row in a typed dataset, change the column's NullValue property in the designer.
null and DBNull are not the same. System.DBNull is an actual object.
The problem is that AlternatePhoneNumber is a string. DBNull is not.
Try this instead:
AlternatePhoneNumber = (customer.AlternatePhoneNumber as string) ?? ""
Do this:
public T IfNull<T>(object o, T value)
{
return (o == DbNull.Value) ? value : (T)o;
}
DBNull is a type with a single value, and is not the same as a null string reference, which is why you can't use ??. You could do this however:
string alternativePhoneNumber = DBNull.Value.Equals(customer) ? string.Empty : ((Customer)customer).AlternatePhoneNumber;
As other replies state, null means a reference that refers to no object, while DBNull is a class supplied by ADO.NET to indicate when a field or value is NULL at the database (or in a DataTable).
While you can use the conditional (ternary) operator (?:) to do what you want:
AlternatePhoneNumber = customer.AlternatePhoneNumber is DBNull
? ""
: customer.AlternatePhoneNumber;
I tend to wrap this up in an extension method:
static class NullExtensions
{
public static T WhenNull<T>( this object value, T whenNullValue )
{
return (value == null || value is DBNull)
? whenNullValue
: (T)value;
}
}
which I find makes the code easier to read and understand.
AlternatePhoneNumber = customer.AlternatePhoneNumber.WhenNull( "" );
DBNull is NOT a real "null".
The "??" - operator detects only null - references, not objects that emulate "null" behavior.
Related
I am trying to read nullable values from a database. Right now my code is converting null values to false. How can I modify my code to allow for null values?
Ap1ExamTaken = dr["AP1_ExamTaken"] != DBNull.Value && Convert.ToBoolean(dr["AP1_ExamTaken"]),
I would like values that are null to be shown as null and not false.
You could use the conditional operator here, to set it to null if the value is DBNull.Value, or a non-nullable value otherwise:
Ap1ExamTaken = dr["AP1_ExamTaken"] == DBNull.Value ? null : (bool?) dr["AP1_ExamTaken"];
Note that this will throw an exception if dr["AP1_ExamTaken"] is a non-boolean, non-DBNull type, which I suspect is what you want.
You could write it more compactly as:
Ap1ExamTaken = dr["AP1_ExamTaken"] as bool?
... but then you'll end up with a null value if the value is some other type (a string, an integer etc) which I'd generally be alarmed about. (If my data doesn't have the shape I expect, I want to know ASAP.)
I want to check the following field in the datatable against null :
r.Field<int>("prod_type")
if (r.Field<int>("prod_type") != null &&
!string.IsNullOrEmpty(r.Field<int>("prod_type").ToString()))
but I get the following exception :
Specified cast is not valid.
How to check the integer value in the datatable against null or empty ?
The Field extension method supports nullable types. Use HasValue to check if a nullable is not null:
if (r.Field<int?>("prod_type").HasValue)
The error you are getting is indicating that the field in the datatable is not of type int. If it is of type int it can't hold null value, instead you can try int? which is Nullable.
r.Field<int?>("prod_type") != null
If prod_type is indeed an int field in the database, try doing it like this:
if (r.Field<int?>("prod_type") != null)
I got a weird error message when I tried to convert an object to bool, here is my code:
public partial class ModifierAuteur : DevExpress.XtraEditors.XtraForm
{
public ModifierAuteur(object getKeyDecesCheckBox)
{
decesCheckBox.Checked = getKeyDecesCheckBox == null ? null : (bool)getKeyDecesCheckBox;
}
}
and this is the error message :
Type of conditional expression cannot be determined because there is
no implicit conversion between <null> and bool
Assuming that the assignment is possible, you need to convert to a nullable bool, like this:
decesCheckBox.Checked = getKeyDecesCheckBox == null ? null : (bool?)((bool)getKeyDecesCheckBox);
The inner cast to bool unboxes the value, and the outer cast to bool? makes it compatible with null of the conditional expression.
If the left-hand side of the assignment does not allow nulls, you need to decide on the value to set when getKeyDecesCheckBox is null. Usually, that's a false:
decesCheckBox.Checked = getKeyDecesCheckBox == null ? false : (bool)getKeyDecesCheckBox;
Assuming the Checked property is of type nullable bool, I would probably do the following:
decesCheckBox.Checked = (getKeyDecesCheckBox == null ? (bool?)null : (bool?)getKeyDecesCheckBox);
If it takes a bool (not-nullable) you can convert the null to false easily with:
decesCheckBox.Checked = (getKeyDecesCheckBox == null ? (bool?)null : (bool?)getKeyDecesCheckBox).GetValueOrDefault();
decesCheckBox.Checked is of type bool. As such you must feed it either false or true.
Your '? :' operator has two possible incompatible return types: if the object is null, then it returns the value null, which can be cast to any nullable type. If the object is not null, then its return type is bool.
I don't know what type 'Checked' is, but I suspect that its type is 'bool'.
The problem here is that you can't cast null to the 'bool' type, and so you have to decide what type you want it to be in the case the object is null. If you wanted it to be false, you could write the statement as:
decesCheckBox.Checked = (getKeyDecesCheckBox as bool) ?? false;
The ?? Operator assigns the value 'false' in the case where the object is null, or cannot be converted to a bool.
I have CustomerID declared as
int? CustomerID=null;
I am checking null values while reading DataReader
Id = reader["CustomerId"] is DBNull ? null :Convert.ToInt32(reader["CustomerID"]);
It is throwing
Type of conditional expression cannot be determined because there
is no implicit conversion between '<null>' and 'int'
What is the problem with the Conversion?
I think you need to do it this way:
if(! reader.IsDBNull(reader.GetOrdinal("CustomerId"))
{
Id = Convert.ToInt32(reader["CustomerID"]);
}
else
{
Id = NULL;
}
You need to use the .IsDBNull method on the reader to determine ahead of time if a column is NULL - if it is, don't even read the value from the reader.
Change your conditon to
reader["CustomerId"] == DBNull.Value
A ?: conditional expression cannot evaluate to two different types on the true and false condition. I think a cast (int?)null should work.
The problem (assuming that Id is declared properly) is that the conditional statement infers the result type from the true result. In your case, that type is null. It then will try to cast the second type to the same as the first...and there is no cast from int to null.
The solution is to cast the true expression to the desired type:
Id = reader["CustomerId"] == DBNull.Value ?
(int?) null :
Convert.ToInt32(reader["CustomerID"]);
Try this
Id = reader["CustomerId"] is DBNull ? (int?)null : Convert.ToInt32(reader["CustomerID"]);
the types of both parts of the ?: need to be explicit
What's happening is your code is incorrectly evaluating and trying to do the Convert function.
Its readding reader["CustomerId"] is DBNull which it isn't its really a DBNull.Value so then it attempts to do Convert.ToInt32("<null>") and crashes. You need to fix your if statement, and add a (int ?) cast.
It should be:
Id = reader["CustomerId"] is DBNull.Value ? (int?) null :Convert.ToInt32(reader["CustomerID"]);
I'm writing a C# routine to call a stored proc. In the parameter list I'm passing in, it is possible that one of the values can legally be null. So I thought I'd use a line like this:
cmd.Parameters.Add(new SqlParameter("#theParam", theParam ?? DBNull.Value));
Unfortunately, this returns the following error:
CS0019: Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull'
Now, this seems clear enough, but I don't understand the rationale behind it. Why would this not work? (And often, when I don't understand why something isn't working, it's not that it can't work...it's that I'm doing it wrong.)
Do I really have to stretch this out into a longer if-then statement?
EDIT: (As an aside, to those suggesting to just use "null" as is, it doesn't work. I originally figured null would auto-translated into DBNull too, but it apparently does not. (Who knew?))
Not like that, no. The types have to match. The same is true for the ternary.
Now, by "match", I don't mean they have to be the same. But they do have to be assignment compatible. Basically: in the same inheritance tree.
One way to get around this is to cast your string to object:
var result = (object)stringVar ?? DBNull.Value;
But I don't like this, because it means you're relying more on the SqlParameter constructor to get your types right. Instead, I like to do it like this:
cmd.Parameters.Add("#theParam", SqlDbTypes.VarChar, 50).Value = theParam;
// ... assign other parameters as well, don't worry about nulls yet
// all parameters assigned: check for any nulls
foreach (var p in cmd.Parameters)
{
if (p.Value == null) p.Value = DBNull.Value;
}
Note also that I explicitly declared the parameter type.
new SqlParameter("#theParam", (object)theParam ?? DBNull.Value)
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand. But in your case they are different types, so it doesn't work.
The Null Coalesce operator only with with data of the same type. You cannot send NULL to the SqlParamater as this will make Sql Server says that you didn't specify the parameter.
You can use
new SqlParameter("#theParam", (object)theParam ?? (object)DBNull.Value)
Or you could create a function that return DBNull when null is found, like
public static object GetDataValue(object o)
{
if (o == null || String.Empty.Equals(o))
return DBNull.Value;
else
return o;
}
And then call
new SqlParameter("#theParam", GetDataValue(theParam))
The reason you can't use the null coalesce operator is that it has to return one type and you are providing more than one type. theParam is a string. DbNull.Value is a reference to a static instance of type System.DbNull. This is what its implementation looks like;
public static readonly DBNull Value = new DBNull();
//the instantiation is actually in the
//static constructor but that isn't important for this example
So if you were to have a NullCoalesce method, what would its return type be? It can't be both System.String and System.DbNull, it has to be one or the other, or a common parent type.
So that leads to this type of code;
cmd.Parameters.Add(
new SqlParameter("#theParam", (object)theParam ?? (object)DBNull.Value)
);
In your stored proc when you declare the incoming variable, have it set the var equal to null and then do not pass it in from your csharp code, it will then pick up the default value from sql
#theParam as varchar(50) = null
and then in your csharp
if (theParam != null)
cmd.Parameters.Add(new SqlParameter("#theParam", theParam));
This is how I usually pass option and/or defaulted values to my stored procs
I'm pretty sure that just passing a null to the SqlParameter constructor results in it being sent as a DBNull.Value... I may be mistaken, since I use the EnterpriseLibraries for DB access, but I'm quite sure that sending a null is fine there.
cmd.Parameters.Add(new SqlParameter("#theParam", (theParam == null) ? DBNull.Value : theParam));
Use this syntax:
(theParam as object) ?? (DBNull.Value as object)
In this case both parts of operator ?? are of the same type.
Not sure the specific answer to your question, but how about this?
string.IsNullOrEmpty(theParam) ? DBNull.Value : theParam
or if blank is ok
(theParam == null) ? DBNull.Value : theParam