Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 780
RKh Avatar asked May 25 '12 11:05

RKh


People also ask

How do you know if a value is null or undefined?

The typeof operator for undefined value returns undefined . Hence, you can check the undefined value using typeof operator. Also, null values are checked using the === operator.

How check VAR is null or not in C#?

C# | IsNullOrEmpty() Method In C#, IsNullOrEmpty() is a string method. It is used to check whether the specified string is null or an Empty string. A string will be null if it has not been assigned a value. A string will be empty if it is assigned “” or String.

Is null == undefined?

It means null is equal to undefined but not identical. When we define a variable to undefined then we are trying to convey that the variable does not exist . When we define a variable to null then we are trying to convey that the variable is empty.

How do you check if something is null in C++?

In C or C++, there is no special method for comparing NULL values. We can use if statements to check whether a variable is null or not.


1 Answers

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.

like image 154
Parv Sharma Avatar answered Oct 02 '22 19:10

Parv Sharma