Dolaps
Dolaps

Reputation: 279

check null variable C#

I have created a variable that checks if a row in a database exists. However when I put the variable in an if statement to check if it's null and the variable is null it always goes to else instead of continuing the if statement.

Is there another way of checking if a variable is null instead of == null?

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);
if (following == null)
{
    using (Html.BeginForm("Followruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="follow" class="btn btn-default" />
    }
}
else
{
    using (Html.BeginForm("unfollowruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="following" class="btn btn-default" />
    }

}

Upvotes: 0

Views: 170

Answers (4)

MrFox
MrFox

Reputation: 5106

The object returned is never null, it's value might be though. Use 'FirstOrDefault()' to make the result null if there is none:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).FirstOrDefault();

Or ask the result if it has any values:

if(following.Any())

Upvotes: 0

Mehbube Arman
Mehbube Arman

Reputation: 490

If you want to keep what you have given, you can also count number of values returned by the predicate.

if (following != null && following.Count < 1)

This should work for you I think.

Upvotes: 0

Dirk
Dirk

Reputation: 10958

The Where operator will never return null. It is also the wrong method to use if you simply want to check if a record exists. I'd use Any instead.

bool following = objCtx.Followusers.Any(
    c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);

Upvotes: 3

HaukurHaf
HaukurHaf

Reputation: 13796

Change it to:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).SingleOrDefault();

That should return NULL if no row is found.

Upvotes: 2

Related Questions