5YrsLaterDBA
5YrsLaterDBA

Reputation: 34770

what will be returned in this method with using statement?

what this method will return when the db is null for some reason? compile is fine and there is no return statement outside the using block.

public Guid GetUserId(string username)
    {

        using (AndeDBEntities db = new AndeDBEntities())
        {
            var userId =
                from u in db.Users
                where u.Username == username
                   && u.Deleted != true
                select new { UserID = u.UserId };
            if (userId == null || userId.Count() == 0) 
                return Guid.Empty;
            else 
                return userId.First().UserID;
        }
    }

Upvotes: 0

Views: 99

Answers (3)

ChrisF
ChrisF

Reputation: 137148

Under normal conditions db cannot be null.

The only way it can is if the new failed, in which case you've got more serious problems.

Upvotes: 0

dthorpe
dthorpe

Reputation: 36082

db will not be null. If the new allocation fails, an out of memory exception will be thrown and the using block will never be executed, and the function will not return a value (because the exception will blow out of the function too).

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564433

If the db is null for some reason, this will likely raise an Exception at runtime. This will most likely be a NullReferenceException, but could be some other exception depending on how it was written.

However, this really shouldn't be possible. db should always be valid, although db.Users may be null if the constructor (AndeDBEntities) doesn't set it properly. In this case, you'll get a NullReferenceException when you hit your LINQ query (ie: accessing db.Users).

Upvotes: 2

Related Questions