I am facing inconsistent null value reference errors while I am trying to store my values from a serialized class object.
if ( item.current_location.city!=null )
{
var city = item.current_location.city.Select(i => i.ToString());
}
In the above code snippet, successful insertion takes place even if any index in item array has null values. But it throws exception in some cases,which I don't think can be distinguished in any manner from other cases( when the value is null)
item could be null as well
current_location could be null as well,
not only city.
This would help
if (item != null &&
item.current_location != null &&
item.current_location.city != null) {
...
}
EDIT:
Note: This code works, since c# implements a so-called shortcut-evaluation of Boolean expressions. If item should be null, the rest of the expression would not be evaluated. If item.current_location should be null, the last term would not be evaluated.
(I do not see any insertion in the code above.)
Starting with C#6.0 you can use the null propagation operator (?):
var city = item?.current_location?.city?.Select(i => i.ToString());
if (city != null) {
// use city ...
}
I can't give a definitive answer without seeing your dataset, but you're not checking for null values on the item object or the current_location object. I would suggest you start by changing your test to this:
if (null != item && null != item.current_location && null != item.current_location.city)
{
...
}
Related
Following is my null operator check
if (vessels?.Vessels?.Count == 0)
{ }
and object is below
private static readonly DataQueueItem _emptyVessel = new DataQueueItem()
{
VesselId = 1,
Vessels = null
};
It is going in else part but it should be in if block.
I am confused why it is happening.
Any help
Please change your code into =>
if ((vessels?.Vessels?.Count ?? 0) == 0)
{
// do something.
}
Explanation: As vessels can be null or vessels.Vessels can be null so, vessels?.Vessels?.Count will return (int?) type. At the same time, in the if condition if (vessels?.Vessels?.Count == 0) in the question, we are trying check a (int?)==(int). Which might not worked as you expected. We can not check null to a value. That's why I have added (vessels?.Vessels?.Count ?? 0). That part will return 0 if vessels?.Vessels?.Count is null. So, value will be checked with a value.
Do this instead:
if (vessels.Vessels == null)
{
// Code
}
The null keyword is a literal that represents a null reference, one that does not refer to any object. null is not the same as 0.
This is mainly a syntactic sugar/best-practice question.
Here is a code example in question:
if (_instanceData?.DataSourceType != null && Util.IsEntityBacked(_instanceData.DataSourceType) {// code}
I understand that the safe navigation operator will continue execution if _instanceData is null, but in this case will the first boolean in the conditional be evaluated as expected? Is this going to successfully null check on both _instanceData and DataSourceType?
Another Example:
if (LockAcquired && _instanceData?.ObjInfo != null) {// code}
In this case, it is possible that _instanceData is null, or it is not, but ObjInfo is null. Is it better practice to just old-fashioned null check both object and property, or will this get the job done as expected?
edit: The question is better described as:
Is if (obj?.prop != null) equivalent to
if (obj != null && obj.prop != null)
The first is equivalent to
if (_instanceData != null && _instanceData.DataSourceType != null && Util.IsEntityBacked(_instanceData.DataSourceType) {// code}
The second is equivalent to
if (LockAcquired && _instanceData != null && _instanceData.ObjInfo != null) {// code}
So it will check if _instanceData is null, then check if _instanceData.DataSourceType is null, then the last condition. As you said, this is just syntactical sugar so you don't have to write two != null conditions. The IL code that results is exactly the same, so its a matter of preference whether or not to use the operator.
It does save a TON of space when accessing deeply nested properties, which is where its most useful
if(Parent != null)
{
if(Parent.Child != null)
{
if(Parent.Child.GrandChild != null)
{
Parent.Child.GrandChild.GreatGrandChild.name = "Parent IV";
}
}
}
becomes
Parent?.Child?.GrandChild?.GreatGrandChild.name = "Parent IV";
Saves a lot of space! Even if you collapsed all the ifs into one statement it still saves loads of keystrokes and screen noise.
Is there a better way to write this null check? I'm checking a table from a DataSet for nulls.
if (dataSet == null || dataSet.Tables == null || dataSet.Tables[0].Rows == null)
{
Console.WriteLine($"Error at {nameof(dataSet)}");
return vatPeriodList;
}
I'm working in ADO.NET.
Your check doesn't make sense and also forgets one important.
DataSet.Tables also can't be null because it's a readonly property, you can't assign null, so the second check is pointless.
dataSet.Tables[0].Rows can't be null because it's a readonly property, you can't assign null, so the last check is redundant.
But you forgot that the DataSet could be empty, so doesn't contain any DataTables. In that case your if throws an exception at dataSet.Tables[0].
I would use:
int? firstTablesRowCount = dataSet?.Tables.Cast<DataTable>().FirstOrDefault()?.Rows.Count;
if (firstTablesRowCount.GetValueOrDefault() == 0)
{
Console.WriteLine($"Error at {nameof(dataSet)}");
}
This ensures that the DataSet isn't null and contains tables and that the first table contains rows.
Try
if(dataSet?.Tables?.FirstOrDefault()?.Rows == null) {}
FirstOrDefault() returns the first entry or null if there is none.
I am using bellow code to get date value from ListviewDataItem control
object HyperWalletPayoutDate =
DataBinder.Eval(dataItem.DataItem, "HyperWalletPayoutDate");
some time HyperWalletPayoutDate value come null. How can i check this null value ?
I have tried this way but not working
if (HyperWalletPayoutDate.Any() == null || HyperWalletPayoutDate == ""
|| HyperWalletPayoutDate ==null)
Please give me suggestion to solve this problem. Thanks in advance ..
The behaviour you are seeing (the value is {} rather than null) is a result of Boxing. Assuming you are expecting a string value you should use the correct check for that particular type i.e.
if (String.IsNullOrEmpty((string)HyperWalletPayoutDate)) {
...
}
This will internally unbox the value and determine whether it has a value.
The problem with your code is that the first condition
if (HyperWalletPayoutDate.Any() == null || ...
already requires an instance. You have to perform the null check on HyperWalletPayoutDate first:
if (HyperWalletPayoutDate == null || HyperWalletPayoutDate == "" || HyperWalletPayoutDate.Any() == null)
when HyperWalletPayoutDate is null, the other conditions are not evaluated, so no exception is thrown anymore.
I think it works like this:
if(HyperWallenteretPayoutDate.Any(d => d)){
//it does not equal null
}
In IEnumerable.First function, how do I handle the case if there are no matches? Currently it just crashes...
MySPListItem firstItem = itemCollection.First(item => !item.isFolder);
if (firstItem != null)
{
TreeNode firstNode = GetNodeByListItem(my_treeview.Nodes, firstItem, ReportObject);
if (firstNode != null)
{
ReportObject.log("Selecting the first PDF");
selectPDF(my_treeview, firstNode, queryStr_param);
}
}
Error Message:
Sequence contains no matching element
Stacktrace: at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func2
predicate)
Ok, If it is exceptional for there to be no first,
try
{
var first = enumerable.First();
}
catch (InvalidOperationException)
{
// Oops, that was exceptional.
}
If you anticipate that there may be no first in some valid situations,
var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
// Ok, I need to deal with that.
}
While you do a null check on the find, you don't in your predicate. The line
foundItem = itemCollection.Find(item => item.item.ID == PDFID);
Might throw an exception it item is null (have you inserted an null item in the collection?) or item.item is null (are you sure it's always there?).
You could do:
foundItem = itemCollection.Find(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
More chatty, but you won't get a NullReferenceException.
Edit Well you changed your question. Now you do First. The First method will throw an exception if nothing is found. Use FirstOrDefault instead which will return null for a class or the default value for a struct.
foundItem = itemCollection.FirstOrDefault(item => item != null &&
item.item != null &&
item.item.ID == PDFID);
Replace First by FirstOrDefault :
MySPListItem firstItem = itemCollection.FirstOrDefault(item => !item.isFolder);
Quoted from the MSDN website you linked to:
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
This describes the return value. Hence, when no match is found, the default value for type T is returned, which means null for reference types, and things such as 0, false & co. for value types.
So in your calling code, simply check for this default value, and you're fine :-). What you can not do is just use the value that is being returned, as this e.g. might result in a NullReferenceException, if you are using a reference type.
Check if the result is null:
if (result == null)
{
Console.WriteLine("Not found");
}
There is a clear example demonstrating what to do if the item is found/not found here
It shouldn't throw an exception, you need to handle the case where it returns default(T). You might be getting a NullReferenceException because you're not handling the case where it returns null. For example:
IEnumerable<Cars> cars = GetCars();
Car car = cars.Find(c => c.Model == "Astra");
if(car != null)
{
// You found a car!
}
If you were doing the same for a struct, you'd check for it's default instead. Ints for example would be a 0:
int[] ints = new int[] { 1, 4, 7 };
int myInt = ints.Find(i => i > 5);
if(myInt != 0) // 0 is default(int)
{
// You found a number
}