How to check a var for null value? - c#

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)
{
}

Related

What does Return myVar != null actually mean?

Resharper is a great tool, but it sometimes confuses me as to what the suggested code really means. I have this code:
private bool DoesUserExists()
{
var user = De.Users.FirstOrDefault(u => u.Username == CurrentUser.Username);
return user != null;
}
I originally had :
if(user == null)
return false;
else
return true;
But Resharper suggested the top code. However, that looks to me to be saying return user if it is not null. But the method only accepts a bool return and not a class.
So what does return user != null actually return when it is null and when it is not?
So what does return user != null actually return when it is null and
when it is not
It simply evaluates the expression. If user is null it returns false and if user isn't null, it returns true.
Think of this as if you were assigning the result of the comparison to a local variable, and only then returning it:
bool isNotNull = user != null;
return isNotNull;
Or:
bool isNull = user == null;
return !isNull;
isNotNull would be true only iff the user variable is not null.
Semantically, it is identical to your if-else statement.
Not sure I'm adding any value here, #Yuval's answer is correct and clear, but maybe it helps to see it this way.
You are thinking of parsing the code something like this:
(return user) (!= null)
That is, you see "return user" and wonder what the rest of the line is doing there. But return doesn't work that way. It evaluates the rest of the line, and returns that. It's more like
(return) (everything else)
or, in the specific case
(return) (user != null)
Where return gets executed last.
It is much like operator precedence, where 3+5*2 must be evaluated as 3+10 instead of 8*2, because * has higher precedence (must be evaluated first) than +. return has the lowest precedence of all.
If you learn to read and write code with this in mind, you will find yourself appreciating the refactored code.

Check if non-valued query string exists in url with C#

I've seen a couple examples of how to check if a query string exists in a url with C#:
www.site.com/index?query=yes
if(Request.QueryString["query"]=="yes")
But how would I check a string without a parameter? I just need to see if it exists.
www.site.com/index?query
if(Request.QueryString["query"] != null) //why is this always null?
I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!
If you do not specify a value, the key will be automatically set to null, so you cannot check its existence.
In order to check if the value actually exists, you can check in the collection of Values equalling null if it contains your Key:
Request.QueryString.GetValues(null).Contains("query")
this is the fastest way to check it thanks to Ludovic's answer
if(Request.QueryString.GetValues(null)?.Contains("query")??false)
It returns null because in that query string it has no value for that key. I think the check you're looking for is this:
if(Request.QueryString.Keys.OfType<string>().Any(k => k == "query"))
or even:
if(Request.QueryString.AllKeys.Any(k => k == "query"))
The latter is probably more appropriate because that array is already cached.
If query was included as a parameter, but no value was specified, then the value of query will be null but it will still exist in Request.QueryString.AllKeys.
If query was not included, it won't exist in Request.QueryString.AllKeys at all.
Ludovic has the right answer. But I would like to offer a more robust version.
var valueEntries = Request.QueryString.GetValues((string)null) ?? new string[] {};
if (valueEntries.Contains("query", StringComparer.OrdinalIgnoreCase))
{
// value is specify in querystring
}
else
{
// value is NOT specify in querystring
}
This is verbose and it works. Here is a .NET Fiddle.
#using System.Linq;
#{
var empties = Request.Url.Query
.Split('&')
.Where(s => !s.Contains("=") || s.Last() == '=');
var keyExistsAndIsEmpty = empties.Any(x => x.Contains("target-key")
}
It turns out that if the value is null, then the key is also null in the QueryString collection. Your best bet is simply to assign a value to the query. There might be a way for you to rename the parameter so that this makes more semantic sense. For example instead of www.site.com/index?getdocument=yes you could do www.site.com/index?action=getdocument
However if you still want the url www.site.com/index?query to work, there is a way: don't use the QueryString at all and parse the URL manually:
string query = Request.RawUrl.Split('?')[1];
if (query == "query")
{
// send the data
}
You cannot use a null check to determine if a key exists when the "=" is not supplied since null means that the key wasn't in the query string.
The problem is that "query" is being treated as a value with a null key and not as a key with a null value.
In this case the key is also null inside Request.QueryString.AllKeys.
I used this generic method to "fix" the null key problem in the query string before using it. This doesn't involve manually parsing the string.
Usage example:
var fixedQueryString = GetFixedQueryString(Request.QueryString);
if (fixedQueryString.AllKeys.Contains("query"))
{
}
The method:
public static NameValueCollection GetFixedQueryString(NameValueCollection originalQueryString)
{
var fixedQueryString = new NameValueCollection();
for (var i = 0; i < originalQueryString.AllKeys.Length; i++)
{
var keyName = originalQueryString.AllKeys[i];
if (keyName != null)
{
fixedQueryString.Add(keyName, originalQueryString[keyName]);
}
else
{
foreach (var keyWithoutValue in originalQueryString[i].Split(','))
{
fixedQueryString.Add(keyWithoutValue, null);
}
}
}
return fixedQueryString;
}
I Prefer to use:
If(Request.QueryString.AllKeys.Contains("query")
{
//
}

MVC C# want my query to be able to return null elements

So I have a simple line of code that I'm using to check if the database already has data, but when it doesn't it returns an error (stating that nothing could be found in the database).
Basically I'm trying to get it so that the query can return null aswell? here's the code I'm using:
var ac = db.Houses.Single(d => d.address1 == reviewmodelview.Address1);
So as you can see its really quite simple, I will use the ac variable to run an if statement to see if its null or has has a value. But when its null, it throws an exception. Is there a piece of code I'm missing?
Instead of Single() use FirstOrDefault() that should do what you want.
Try SingleOrDefault - It will returns the default value for the type if the result set returns 0.
var ac = db.Houses.SingleOrDefault(d => d.address1 == reviewmodelview.Address1);
if(ac == null)
{
// null check
}

Data Caching chances of returning null value from function

I have a function written in C# which return collection of business-entity (make) after checking and inserting in cache.
public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context)
{
var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
if (allMake == null)
{
context.Cache.Insert("SmartPhoneMake", new CModelRestrictionLogic().GetTopMakes(), null,
DateTime.Now.AddHours(Int32.Parse(ConfigurationManager.AppSettings["MakeCacheTime"])),
Cache.NoSlidingExpiration);
allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
}
return allMake;
}
I am using it in some other page as follows
var lobjprodMakeCol = CBrandCache.GetCachedSmartPhoneMake(Context);
//CBrandCache is the class which contain the method
Is it possible that I get null value in the lobjprodMakeCol
Thanks.
Edit
Note new CModelRestrictionLogic().GetTopMakes() is a function which fetches the records from database.
It will return a collection weather of count 0 or more.
There are few of possibilities when your function could return null - they are
GetTopMakes function it self returns null
The cache expiration time is zero (MakeCacheTime config entry has zero value)
The cast as Collection<CProductMakesProps> fails - possible if GetTopMakes
return some different type.
I would prefer below version which would not return null in all of above cases
var allMake = context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
if (allMake == null)
{
allMake = new CModelRestrictionLogic().GetTopMakes();
context.Cache.Insert("SmartPhoneMake", allMake,
null, DateTime.UtcNow.AddHours(Int32.Parse(
ConfigurationManager.AppSettings["MakeCacheTime"])), Cache.NoSlidingExpiration);
}
return allMake;
Also note that use of DateTime.UtcNow that would avoid any surprises such as day-light savings etc.
Yes it is possible, if the cast as Collection<CProductMakesProps> fails then a null will be assigned to allMake, so this depends heavily on what you are returning from new CModelRestrictionLogic().GetTopMakes().
Based on the assumption that most cache and/or dictionary collections will allow you to check for the presense of a specific key, I would suggest a slightly more streamlined way of writing this:
public static Collection<CProductMakesProps> GetCachedSmartPhoneMake(HttpContext context)
{
if (!context.Cache.ContainsKey("SmartPhoneMake") || context.Cache["SmartPhoneMake"] == null)
{
context.Cache.Insert("SmartPhoneMake"
, new CModelRestrictionLogic().GetTopMakes()
, null
, DateTime.Now.AddHours(Int32.Parse(ConfigurationManager.AppSettings["MakeCacheTime"]))
, Cache.NoSlidingExpiration);
}
return context.Cache["SmartPhoneMake"] as Collection<CProductMakesProps>;
}

Null Exception handling in foreach loop

I am having the list X with some string and null value . I am iterating the foreach loop to bind the value to the textbox. If I get any null values in my list X the foreach loop get terminated and getting the null exception how to handle it.
I am checking the condition inside the foreach loop, but I think it's not correct logically.
SPList _listObj = web.Lists[new Guid(listID)];
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
foreach (SPField field in _listObj.Fields)
{
if (field.Title != Null)
{ //do some code}}
Try below code:
foreach(var x in Lists.Where(x => x.fiels != null))
{
}
Why don't you use it like this with null-coalescing operator
foreach (var item in feeList ?? new List<FeeBusiness>())
{
// your code
}
The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.
That code looks pretty suspicious to me.
Firstly, do you really have a list of lists? If so, I'd imagine you have to iterate over each element in the inner list as well:
foreach(List list in Lists)
{
foreach (var x in list)
{
if (x.fields != null)
// blah
else
// blah
}
}
Secondly, are you sure that the Lists variable doesn't contain any nulls? Possibly it's actually x which is null, and that's the cause of your Null Reference Exception:
foreach(List x in Lists)
{
if (x != null && x.fields != null)
// blah
else
// blah
}
The code provided is not correct. I suppose you want to check X for Null in foreach loop. If this is logically correct or not, instead only you may know as logic goes beyond the code provided and depends on where you actually use it.
I personally don't find nothing bad to check for nulls in foreach loop.
You also, for example, can use Linq to query first for Null values and after Non Null values. The matter of design choice.
Regards.
List x in Lists? You probably mean to do:
foreach(string x in listvar){
if(x != null)
// do something
}
And are the strings actually null or just empty? That is a difference.
foreach(string x in listvar){
if(x != "")
// do something
}
I suspect that the problem is in your incorrect implementation of the foreach loop which causes to pop null errors as the objects inside the loop do not exist.
string delimitedvalues = null;//"11,22,33";
foreach(var str in (delimitedvalues?? string.Empty).split(','))
{
string testvalue = "Test Value" + str;
}
Hope the above construct is useful!
You have to make sure that your object you are getting doesn't come back as null (your list, _listObj) before you ever iterate its fields. Even if you are certain the GUID you are passing in matches the list you are trying to get, you should be checking that object for being null, and checking for the number of fields, and if you get an item for the ID you are passing in:
SPList _listObj = web.Lists[new Guid(listID)];
if (_listObj != null) // do we have a list object?
{
if (_listObj.Fields.Count > 0) // do we have list columns on the list?
{
SPListItem item = _listObj.GetItemById(Convert.ToInt32(itemID));
if (item != null) // did our item ID get a hit?
{
foreach (SPField field in _listObj.Fields)
{
if (field.Title != null) // need lower case null, here
{
//do some code
}
}
}
}
}

Categories