If condition to check for DBNull.Value - c#

I'm trying to check for DBNull.Value but in this case reader["Preferences"] returns {} in the immediate window (why?)
so when (string)reader["Preferences"]; executes I get a type casting error
if (reader["Preferences"] == System.DBNull.Value)
{
preferences = (string)reader["Preferences"];
}

You are trying to cast only when the value is DBNull.Value.
You should invert your if:
if (reader["Preferences"] != System.DBNull.Value)
{
preferences = (string)reader["Preferences"];
}

Related

Setting DateTime property to null

So I have this property and would like to either set the value to what is coming back from the db or to null if it is empty. It is possible to do this with an if-else, but for cleaner code, I would like to use the ternary operator. Could someone point out the mistake I am making. Thanks!!!
public DateTime? OptionExpiration {get;set;}
//actually sets the value to null
if(String.IsNullOrEmpty(dr["OPTION_EXPIRATION"].ToString())){
OptionExpiration = null;
}else{
OptionExpiration = DateTime.Parse(dr["OPTION_EXPIRATION"].ToString());
}
//so I check the to see if the string is empty or null, then try to set the value but recieve this error: Error 2 Operator '|' cannot be applied to operands of type '' and 'System.DateTime?'
String.IsNullOrEmpty(dr["OPTION_EXPIRATION"].ToString())
? OptionExpiration = null
| OptionExpiration = DateTime.Parse(dr["OPTION_EXPIRATION"].ToString())
;
You are using the ternary operator wrong.
It should be:
OptionExpiration = String.IsNullOrEmpty(Convert.ToString(dr["OPTION_EXPIRATION"]))
? (DateTime?)null
: DateTime.Parse(dr["OPTION_EXPIRATION"].ToString())
;
So:
assignment = condition ? trueExpression : falseExpression;
If the field is a date in your database, it might be better to do this:
OptionExpiration = Convert.IsDBNull(dr["OPTION_EXPIRATION"])
? (DateTime?)null
: (DateTime)dr["OPTION_EXPIRATION"]
;
I would use an extension method like this:
public static Nullable<DateTime> AsNullableDateTime(this object item, Nullable<DateTime> defaultDateTime = null)
{
if (item == null || string.IsNullOrEmpty(item.ToString()))
return defaultDateTime;
DateTime result;
if (!DateTime.TryParse(item.ToString(), out result))
return defaultDateTime;
return result;
}
You can pass anything in to this and it will attempt to give you back a date. If it fails for whatever reason (this also checks to make sure the object you send through is not null) you will get a null back; which is fine because you're mapping to a nullable datetime.
To use this you would do something like:
OptionExpiration = dr["OPTION_EXPIRATION"].AsNullableDateTime();
No mess, easy to understand what is happening, abstracting away the clutter, and highly reusable on other parts of your solution.

How to assign a value to sqlparameter NULL values without checking for null or 0?

The following check is needed to check for null values. is there a way i can do it directly?
if(node.ID==0)
{
cmd.Parameters["#ID"].Value = DBNull.Value;
}
else
{
cmd.Parameters["#ID"].Value = node.ID;
}
is there way we can cicumvent this check and a design by which we can avoid this repetitive check for each value? (by the way its just a logic that 0 to be interpreted as NULL for my case but am asking the same about nullable objects like string too)
You can use ?: Operator
cmd.Parameters["#ID"].Value = node.ID == 0 ? (object)DBNull.Value : node.ID;
For nullable types, I'd just use an extension method:
public static object CoalesceNullToDBNull(this object input)
{
return input == null ? DBNull.Value : input;
}
Then use it as:
cmd.Parameters["Foo"].Value = someExpression.CoalesceNullToDBNull();
(You could give it a shorter name, of course.)
That won't help for your case though, because you're trying to coalesce a non-null value to null. I would personally consider redesigning your model - use a nullable type for values which can be null, rather than using a magic number. However, you could still use a generic extension method:
public static object CoalesceDefaultToDBNull<T>(this T input)
{
return EqualityComparer<T>.Default.Equals(input, default(T))
? DBNull.Value : (object) input;
}
That will convert 0, '\0', false, null etc to DBNull.Value. You'd have to use that with extreme care though, as I assume there are plenty of places where a 0 should really be a 0.
If you are doing this regularly, try putting the check inside of a method.
For instance:
// ...
SetFormattedValue(ref cmd, node.ID);
// ...
private void SetFormattedValue(ref IDBCommand cmd, int id) // IDBCommand - or whatever your command type is
{
if(node.ID==0)
{
cmd.Parameters["#ID"].Value = DBNull.Value;
}
else
{
cmd.Parameters["#ID"].Value = node.ID;
}
}
You can use the ?? operator:
cmd.Parameters["#ID"].Value = node.ID ?? (object)DBNull.Value

Object reference error on session

I am getting error:
Object reference not set to an instance of an object.
It errors when I try to get the value of a session. The value of the session is null but I have tried testing it to check if it is null and on the if statement it still always fails with this error.
string test;
if (Session["CustType"].ToString() != null ||
Session["CustType"].ToString() != String.Empty)
{
test = Session["CustType"].ToString();
txtCustomerType.Text = test;
}
The error is on the second line of this code. I just don't know what to do because I can't do anything with it if it just errors even when I tried to check whether it is empty or not.
You need to check following. Remove ToString() as calling ToString() on null gives you Object reference error.
Session["CustType"] != null
Use
(!String.IsNullOrEmpty(Session["CustType"]))
first check null, and then call ToString
var obj = Session["CustType"];
if (obj != null &&
!string.IsNullOrEmpty(obj.ToString()))
{
txtCustomerType.Text = obj.ToString();
}
To use ToString() on an object, it cannot be null. Where you have..
Session["CustType"].ToString() != null
You need to replace it with...
Session["CustType"] != null
It may be because you are referencing an object in a table that cannot be reached. Debug your code with breakpoints and check whether your test variable has a value assigned to it at the moment of the exception. If the count of the held table is 0, this will confirm that is the problem.
You should check:
Session["CustType"] != null
before using Session["CustType"].ToString() because if it is null, you are trying to call ToString() on null object.
Most concise code would be probably:
var test = Session["CustType"] as string;
if (!string.IsNullOrEmpty(test))
{
txtCustomerType.Text = test;
}
you have remove tostring() from session while checking null value
use this
if (Session["CustType"] != null &&
Session["CustType"].ToString() != string.Empty)
instead
if (Session["CustType"].ToString() != null &&
Session["CustType"].ToString() != String.Empty)

How to check a var for null value?

I am using PetaPoco Micro-ORM with C# 4.0.
The code below retrieves a single row from the database:
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
I would like to check whether or not the result contains any rows, and whether is null. What is the best way to do this?
if (result == null || result.Count() == 0) {
// Checks whether the entire result is null OR
// contains no resulting records.
}
I think the problem is not in your check for null, because linq is lazy loading. Your error is in using the expression db.SingleOrDefault<TdUsers>(getUserQuery);.
.Single<T>(expression) does not return null - it errors if the result returns no values.
.SingleOrDefault<T>(expression), however, returns a null value if the expression results in no values - and therefore is best combined with an if (result == null) type check, as you're using here.
var result = db.SingleOrDefault<TdUsers>(getUserQuery);
In above code SingleOrDefault will return null vale or the specified
generic type(it's known on runtime).
Inorder to check whether the returned values is null or not you can simply use
if(result!=null)
{
//do your code stuff
}
else
{
//stuff do be done in case where result==null
}
You could do:
result.ToList() // Convert result to a list
if (result.Any()) {
// result is not null
}
var v = result.ToList();
now check
if (v is not null)
{
}
else if (v.Count()>0)
{
}

how can I check whether the session is exist or with empty value or null in .net c#

Does anyone know how can I check whether a session is empty or null in .net c# web-applications?
Example:
I have the following code:
ixCardType.SelectedValue = Session["ixCardType"].ToString();
It's always display me error for Session["ixCardType"] (error message: Object reference not set to an instance of an object). Anyway I can check the session before go to the .ToString() ??
Something as simple as an 'if' should work.
if(Session["ixCardType"] != null)
ixCardType.SelectedValue = Session["ixCardType"].ToString();
Or something like this if you want the empty string when the session value is null:
ixCardType.SelectedValue = Session["ixCardType"] == null? "" : Session["ixCardType"].ToString();
Cast the object using the as operator, which returns null if the value fails to cast to the desired class type, or if it's null itself.
string value = Session["ixCardType"] as string;
if (String.IsNullOrEmpty(value))
{
// null or empty
}
You can assign the result to a variable, and test it for null/empty prior to calling ToString():
var cardType = Session["ixCardType"];
if (cardType != null)
{
ixCardType.SelectedValue = cardType.ToString();
}

Categories