If condition for ?? operator on null object - c#

I have the following string list:
List<string> Emails = new List<string>();
Trying to see if it has any values, or return an empty string:
string Email = Emails[0] ?? "";
The above code throws an exception:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
But changing the ?? operator to a simple if statement, it works fine:
if (Emails.Count > 0)
Email = Emails[0];
else
Email = "";
What am I missing here?
When the list is empty, should Emails[0] not be null ?
Thanks.

I suggest to change it to:
string Email = Emails.FirstOrDefault() ?? "";
If your list is empty, Emails[0] is not null, it just doesn't exist.
Edit: that works for strings and ref types, if you do have a value type, for example int, you will get default(int) that is 0 as result of FirstOrDefault of empty collection

Emails[0] will try access first item of the list - that is why it throws exception.
You can use "readable" DefaultIfEmpty method for declaring "default" value if collection is empty
string Email = Emails.DefaultIfEmpty("").First();

string Email = Emails[0]
That is the problem. ?? only checks if whats on its left is null and acts accordingly.
You seem to have the misconception that an empty list has null stored at index 0. That is most definitely not the case. These two lists are semantically very different:
var emptyList = new List<string>();
var someList = new List<string>() { null };
In your code you are trying to access the item at position zero of an empty list. This is an index out of range exception because there is no such item. The exception is thrown before the ?? operator is even evaluated.

Using Emails[0] will throw exception as you access element 0 that is not exist
as Maksim suggested Emails.FirstOrDefault() will return null if the list is empty which you check by ?? coalesce operator

Related

Validate that DataTable cell is not null or empty

I would like to check if the value in a Data Table cell is either null or empty/blank space. The String.IsNullOrEmpty() method does not work as the row["ColumnName"] is considered an object.
Do I need to do a compound check like the following or is there something more elegant?
if (row["ColumnName"] != DBNull.Value && row["ColumnName"].ToString().Length > 0)
{
// Do something that requires the value to be something other than blank or null
}
I also thought of the following ...
if (!String.IsNullOrEmpty(dr["Amt Claimed"].ToString()))
{
// Do something that requires the value to be something other than blank or null
}
but I figured if the value of the cell was null an exception would be thrown when trying to convert to a string using ToString()
A null value would be returned as DBNull, and not a null literal.
var tab = new System.Data.DataTable();
tab.Columns.Add("c1");
tab.Rows.Add();
tab.Rows[0]["c1"] = null;
tab.Rows[0]["c1"].GetType() //returns DBNull
And as the DBNull.ToString() is guaranteed to return an empty string, you can safely use !String.IsNullOrEmpty(value.ToString())).
You can always guard against not being sure if an object is null by simply using null coalescing.
!String.IsNullOrEmpty(value?.ToString()))

Why doesn't a null cause a NullReferenceException when mapping to and from a null type?

I'm basically trying to iterate over a lot of data and transform a returned data query to a more limited object within a View Model.
Rather than do a huge section of code, I'm calling .ForEach() on a list, then adding a new entry to the view model's list.
This works great, but, there is one property (Address) that is optional.
When I reach the optional item, I get NullReferenceException if the item from the DB doesn't have an entry.
A code example is:
var tmp = _context.Person.Include(x => x.Address).ToList();
tmp.ForEach(x => vm.List.Add(new IndexListItem()
{
Name = x.Name,
Address = x.Address.FirstLine + " " + x.Address.SecondLine,
ID = x.ID
}));
I have since found out from a different answer on this site that if I change the address line so that it reads:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
The code now works when I hit a null entry in tmp.
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
In addition, is the reason for me not having to do x.Address?.FirstLine? because that's a string and strings are already nullable?
A null reference exception in this particular case is caused when you are trying to access a property where the parent object is null itself.
x.Address.FirstLine
i.e. in your case Address is null.
It is not in regard to what you are trying to set (i.e. the destination view model).
The reason that this works:
x.Address?.FirstLine
..is because 'in the background' it's checking first to see if Address is null. If it isn't, then it returns FirstLine and if it is, then null is returned. It's semantically equivalent to:
if (x.Address == null)
{
return null;
}
else
{
return x.Address.FirstLine;
}
Here's a blog post about the introduction of the ?. operator in C# for some background reading: https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/
I do not understand this as the Address property on tmp was already allowing nulls, and the Address property on the view model allows nulls, so, why does changing the line suddenly not return an error?
You are mixing up saving data with loading data. When you save the data to the database, null is acceptable, but when you try to use the data, null is not.
The null conditional operator (?.) allows you to "shorten" an if statement, and it would be something similar to:
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
string Address = "";
if (x.Address != null)
{
Address += x.Address.FirstLine;
}
// ....
Also, while not relevant to your problem, the code you are using is extremely ineffective, you are loading 2 tables to get just a few properties when you could get those properties directly from the database:
var vm = _context.Person
.Select(x => new IndexListItem
{
Name = x.Name,
Address = x.Address?.FirstLine + " " + x.Address?.SecondLine,
ID = x.ID
})
.ToList();
x.Address?.FirstLine where ? is null propogation operator this means if x.Address is null set null for the FirstLine.
null propogation equivalent code
if (x.Address == null)
return null
else
return x.Address.FirstLine
All reference type variables are nullable. hence, assigning null to reference types are always valid.
string is a reference-type in your example. therefore you do not get error because string x = null is valid
Your issue isn't that Address is null and you're trying to assign it to another property that allows null, it's that you're trying to access .FirstLine in something that's null.
If Address is null, then what you're trying to do with .FirstLine is the equivalent of null.FirstLine which doesn't work. Nothing can't hold something.
The ? notation you're using that works is only effecting Address, basically saying if Address is NOT null give me the value of .FirstLine, if it is null, then give me null.

How to avoid Nullreference exception when searching in List [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I am trying to get a list item that contains a certain string and I am using this code:
string myListLine= myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("mystring "));
All works well but if the list does not contain a particular string it throws an error:
object reference not set to an instance of an object
I think that I should somehow validate if the string first exists but not sure what would be the best approach.
if the list does not contain a particular string it throws an error:
That is not correct. The exception is thrown, because you have a null value inside your list! If all of your items in the list are valid strings then there will be no exception thrown. In this case FirstOrDefault will simply return null.
I think that I should somehow validate if the string first exists
You can check whether it is null the oldscool way first and combine it with an logical AND && with the Contains method
string myListLine= myList.FirstOrDefault(stringToCheck =>
stringToCheck != null && stringToCheck.Contains("mystring "));
This way the second Contains will not be evaluated if the first condition evaluates to FALSE
You can use the safe navigation operator and the null-coalescing operator to fix this:
System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string> { null, "Test123" };
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck?.Contains("mystring ") ?? false);
The problem occurs if you're calling a method on a null list entry.
Note: If the list is empty FirstOrDefault returns null.
Hope that helps.
Your code simply goes through myList, for each item, it checks if it contains "mystring ".
Only reason you may get a null reference while running that line is your list myList is null. It wouldn't get any error if it is empty.
if you get a null reference after that line, that would mean that myListLine is null, which would mean myList did not contain any items that matched "mystring ".
To make sure you do not get a null reference error with myListLine you should check if it is null before accessing it by using something like this;
if( myListLine != null ){
<Do something to myListLine>
} else {
<list doesnt contain the correct string, alert user.>
}
I think this sample code of mine is one of the safest way by accessing the myList object. If it is null then return an indicator that value was not found or empty.
List<string> myList = new List<string>()
{
"name","adress","phoneNumber"
};
myList.RemoveAll(item => item == null);
string myListLine = myList.FirstOrDefault(stringToCheck => stringToCheck.Contains("myString")) ?? "Not found/Empty";
A variation:
var myList = new List<string>(){"foo","Bar", null,"the mystring"};
string myListLine = myList.FirstOrDefault(s => s == null? false : s.Contains("mystring"));
Same notes as already mentioned regarding FirstOrDefault being null if empty list or no match (does not Contains)

Null Linq Values

I cant get this to work. The State field is empty on certain occassions, I am trying to get the result to return "--" if it is empty, or doesn't exist.
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select new BondData()
{
CUSIP = c.Element("CUSIP").Value,
Description = (string)c.Element("ISSUER").Value,
Maturity= c.Element("MATURITYDT").Value,
AskYield = float.Parse(c.Element("ASKYIELD").Value),
State = (string)c.Element("STATE").Value ?? "--"
}
;
This just doesn't want to work. The error I am getting is:
NullReferenceException was unhandled. {"Object reference not set to an instance of an object."}
I KNOW that it does not exist. I thought that putting ?? "--" will return "--" if c.Element("STATE").Value is null.
I can resort to modifying the statement to:
var CusipFields = from c in xml.Descendants("LISTARRAY")
orderby c.Element("ASKYIELD").Value descending
select c;
foreach(var t in CusipFields)
{
switch(t.name)
{
}
}
But I think that it is slower. And its not what I want.
Use this:
State = (string)c.Element("STATE") ?? "--"
instead of
State = (string)c.Element("STATE").Value ?? "--"
My answer assumes, that your problem is, that the STATE element is missing, not empty. Please tell me, whether or not that fixed your problem.
I think it's because c.Element("STATE") is null, not it's Value property.
try:
(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";
You're getting this error not because the Value property is null, but because c.Element(...) is null. You'll need to check for nulls in all of your Element() calls and take appropriate action in order to avoid this error.

C# Testing for null

I'm using C# to write a simple program to read Active Directory and display the value held in a AD field on a Windows form program.
If a property doesn't exist then the program crashes, below is my code, how can I catch this and move on to the next field without doing a try/catch for each and every attribute?
DirectoryEntry usr = new DirectoryEntry("LDAP://" + domain, username, password);
DirectorySearcher searcher = new DirectorySearcher(usr);
searcher.Filter = "(sAMAccountName=" + GlobalClass.strUserName + ")";
searcher.CacheResults = false;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("givenName");
searcher.PropertiesToLoad.Add("telephoneNumber");
//program crashes here if telephoneNumber attribute doesn't exist.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();
Just checking usr.Properties["telephoneNumber"] will not work. You must check the actual value. The reason the error is occuring is because you're calling ToString() on Value which is null.
user.Properties will always return a PropertyValueCollection, regardless of the property name entered into the collections indexer.
I.e.
var pony = usr.Properties["OMG_PONIES"]; // Will return a PropertyValueCollection
var value = pony.Value; // Will return null and not error
You need to check the value itself, the best way through the null coalescing operator:
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? "Not found").ToString();
Store the contents of usr.Properties["telephoneNumber"]; in a variable and check for null:
PropertyValueCollection tel = usr.Properties["telephoneNumber"];
textBoxFirstName.Text = (tel != null && tel.Value != null)
? tel.Value.ToString()
: "";
Use the null-coalescing operator (??) operator.
textBoxFirstName.Text = (usr.Properties["telephoneNumber"].Value
?? String.Empty).ToString();
This way the value is replaced with an empty string if null. You could also just return null instead of String.Empty, the reason your code is crashing is because you're trying to call ToString() on a null value.
Something like this should work. If telephoneNumber is not null, it will convert the value to a string, otherwise it will use an empty string.
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value != null
? usr.Properties["telephoneNumber"].Value.ToString()
: "";
A couple of things will help this be more graceful:
Test usr.Properties["telephoneNumber"] for null before calling child properties like Value. I haven't worked with AD myself, but most string-keyed indexers are designed to gracefully handle non-existent keys. the CLR, on the other hand, will happily throw a NullReferenceException any time you try to reference a member of anything that evaluates to null.
On the off chance that AD DOES blow up on a nonexistent column, enclose the assignment in a Try-Catch block that will show an error on the screen and gracefully continue processing (or not).
Use this code
SearchResult.Properties.Contains("property")
To check if the object actually has the prop loaded from the search result
if (usr.Properties["telephoneNumber"] != null)
textBoxFirstName.Text = usr.Properties["telephoneNumber"].Value.ToString();

Categories

Resources