Object type null value check - c#

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
}

Related

question mark operator not working with count

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.

Can a C# Safe Navigation Operator (?.) be used to check if Object is null, as well as property?

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.

A better way to write null reference with return value in c#

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.

Inconsistent null value reference exceptions

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

If null.Equals(null) why do I get a NullReferenceException

I have the following line of code:
var selectedDomainID = lkuDomainType.EditValue.Equals(null)
? string.Empty
: lkuDomainType.EditValue;
Sometimes this generates a NullReferenceException. What I don't understand is why. Isn't the whole point of my code to check for null and if so assign string.empty? When I check in DEBUG it is stating that EditValue == null so what am I missing?
Use lkuDomainType.EditValue == null, otherwise you are trying to call an instance method on a null object. But the better option might be lkuDomainType.EditValue ?? String.Empty. Also watch out for lkuDomainType being null, unless it is a class not an object.
When you use Object.Property and Object is undefined, you are dereferencing a null pointer and that's why you get the exception. Instead, use:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If EditValue is null then you can't call Equals. In this cas you would have to do:
var selectedDomainID = lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
Or you can simplify it by doing:
var selectedDomainID = lkuDomainType.EditValue ?? string.Empty;
you are trying to call the Equals method on a null object - do it like this instead:
lkuDomainType.EditValue == null
The problem is that you are using the object before checking if it's null. You are calling the Equals method of the object, which fails if the reference is null.
You have to exchange your lkuDomainType.EditValue.Equals(null) for lkuDomainType.EditValue == null.
EditValue == null. That means that there is no object there. You cannot call functions on null objects, even if the function is .Equals().
You're better off just saying "(lkuDomainType.EditValue == null)" in this case.
You should use String.IsNullOrEmpty here. Like this:
var selectedDomainID = String.IsNullOrEmpty(lkuDomainType.EditValue) ? string.Empty : lkuDomainType.EditValue;
Equals is a method, you're trying to call a method on a null object which is throwing an exception.
when EditValue is null you cannot call the Equals method on it so the best way to check is to use
lkuDomainType.EditValue == null ? string.Empty : lkuDomainType.EditValue;
If lkuDomainType.EditValue is null, then "lkuDomainType.EditValue.Equals(someObject)" is the same as coding "null.Equals(someObject)". Well, obviously "null" doesn't have any members or methods (it wouldn't be null if it did). That's why you get a NullReferenceException.
Most of the examples from the other posts will work, including String.IsNullOrEmpty, which is a method that returns a boolean value.
All current answers fail to address a critical point: the difference between calling Equals on a Nullable type (which is a struct) vs. class type.
Calling Equals on a Nullable typed object whose value is null will not issue an exception, while doing the same on a class typed object will.
Consider the following code:
int? num = null; // int? is Nullable<int>
String s = null; // String is a class
var equalsNullable = num.Equals(null); // works
var equalsClass = s.Equals(null); // throws
The reason is that Nullable's HasValue method is called in such case, see Jon Skeet's answer for more info.
As other people said, the way to go in the OP's case is to use == or ??.

Categories

Resources