How to check a var for null value?
Asked Answered
V

4

25

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?

Violante answered 25/5, 2012 at 11:31 Comment(0)
H
34
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.

Hornwort answered 25/5, 2012 at 11:34 Comment(3)
Tried result != null, but it displays "Object reference not set to an instance of an object".Violante
@RPK - can you post your code in the question then. This should work.Mars
or !result.Any() :)Sheep
C
6
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
}
Catenary answered 25/5, 2012 at 11:48 Comment(0)
D
4

You could do:

result.ToList() // Convert result to a list

if (result.Any()) {
   // result is not null
}
Designer answered 25/5, 2012 at 11:40 Comment(2)
NO result==null wont be false always.. what do you think is the default value of any reference type?Hornwort
This approach won't work in every case, because result could be null, at which point you will get a NullReferenceException thrown when .ToList() or .Any() are called.Pull
M
2
 var v = result.ToList();

now check

if (v is not null)
{

}
else if (v.Count()>0)
{


}
Magnific answered 25/5, 2012 at 11:37 Comment(1)
See my comment to the answer above.Pull

© 2022 - 2024 — McMap. All rights reserved.