I am trying to optimize the code using SonarQube
List<string> itemList = serviceObject.GetItems();
I tried to validate the list with the below code
if(itemList != null && itemList.Any()
{
//Some operations
}
when above code executed I am getting Sonarqube error remove this expression which always evaluates to "true"
So I refactor the code as
if(itemList == null || !itemList.Any())
return;
//Some Operations
when above code executed I am getting Sonarqube error remove this expression which always evaluates to "false"
Could anyone let me know what is wrong here?
You can shorten this to
if (itemList?.Count >0)
{
...
}
or
if (itemList?.Any() ==true)
{
...
}
?. is one of the Null conditional operators (the other is ?[]), the Elvis operator for short, that allows you to access potentially null variables without throwing. The result of the entire expression after the Elvis operator is nullable and returns null if the variable is null.
This means that itemList?.Count returns an Nullable<int>, and itemList?.Any() a Nullable<bool>. Nullable<T> defines relational operators between itself and its base type T but can't be used as T without an explicit cast. That's why (itemList?.Any() ==true) is needed.
If you use Nullable Reference Types though, itemList can't be null, so a simple comparison would be enough:
if (itemList.Count >0)
{
...
}
If you enable Nullable Reference Types by setting #nullable enable in a source file or <Nullable>enable</Nullable> in the csproj file, the compiler ensures that all variables, fields and methods that return reference types are not null, forcing you to either fix the problem or explicitly specify that a variable is nullable.
With NRTs enabled this line :
List<string> itemList = serviceObject.GetItems();
Would only compile without warnings if GetItems never returned a null. If the compiler doubts this, it would issue a warning advising you to either fix the problem or explicitly declare itemList as nullable with :
List<string>? itemList = serviceObject.GetItems();
I believe it is due to null Comparision.
itemList != null
There is a high chance that serviceObject.GetItems(); is guaranteed to not return null by having a [NotNull] Annotation. Hence the null check is redundant.
How can I show that a method will never return null (Design by contract) in C#
if( itemList !=null ) {//Do something...}
List<string> itemList = new List<string>();
itemList = serviceObject.GetItems();
if(itemList!=null && itemList.Count() > 0 )
{
//Some operations
}
Count is enough to validate a list
List will always not be null but will have no elements. but you have to instatiate it so it wont throw an exception.
Related
I am getting a Null reference exception when the Jobject is empty.
var subjects = item.SelectToken("$.subjects").ToObject<List<JObject>>()
I am want to set var subjects as empty when Jobject empty without throwing an error.
THanks
var subjects = item.SelectToken("$.subjects")?.ToObject<List<JObject>>() ?? new List<JObject>();
List<...>
List is a collection and you need to define what's in the List. Like List<string>, List<object>, or, for your code, List<JObject>.
SelectToken("$.subjects")?.
This means that if SelectToken returns null, it stops there without doing .ToObject, and returns null.
The issue here is that SelectToken will return null when it can't find any object, and when you do .ToObject on a null you get a NullException. So one'd usually check if an object is null before further using its properties or functions.
The question mark - Null-Conditional Operator (Official documents) is a quick syntactic sugar to achieve that, without having to write conditions like
if (... == null)
{ ...convert to list... }
else
{ ...make empty list...}
?? new List()
Not sure what you mean by empty, if you don't want null, but an empty List, Null-coalescing Operator might come to help.
It means that if the statement before ?? is null, returns the statement after ?? instead.
For example, string a = b ?? c means:
string a = b != null ? b : c
But notice that a still can be null if c is null.
It's also a syntactic sugar to help you avoid writing long statements for these checks are frequently needed.
Please consider the following code:
public IList<string> DoSomething(SomeModel model)
{
if (model == null)
{
return new List<string> {"model is null"};
}
...
}
When I wrote the above code I keep getting a suggestion from Resharper that says "Expression is always false"
But I don't understand why because the expression here can most definitely be true if I pass a null object.
Now consider me calling this method:
DoSomething(null);
Here I get a warning from resharper that says Cannot convert null literal to non-nullable reference type.
Is there some new change in c# code that I'm just simply not aware of? We have to explicitly now specify null objects and if so what is the new "null" value?
With C# 6.0 in the VS2015 preview we have a new operator, ?., which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
DotNetFiddle Example:
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?
The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).
For example
var a = model?.Value;
is the same as saying
var a = model == null ? null : model.Value;
In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.
The type of member (Method, Field, Property, Constructor) .Value is irrelevant.
The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:
https://dotnetfiddle.net/7EWoO5
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.
When assigning a value from a null-conditional, it makes sense to return a nullable value type. Otherwise, if the object is null, the null-conditional would return the value type's default and you don't want that. Therefore, this is good:
bool? IsTerminated = Employee?.IsTerminated;
However, why does it return a nullable type if I am just checking a condition? You would think that the compiler could figure this out just fine:
if (Employee?.IsTerminated) { /*do something here*/ }
After all, it's just compiling down to this, right?
if (Employee != null && Employee.IsTerminated) { /*do something here*/ }
In order to get it to work, I have to do this:
if ((Employee?.IsTerminated).GetValueOrDefault()) { /*do something here*/ }
Between the extra code and having to wrap the expression in parens, the whole purpose of the null-conditional's short-hand syntax appears to be defeated. Is this the proper way to handle a null-conditional return value or is there another way that doesn't involve accounting for a nullable return value?
If A?.B contains B of a reference type, then you'll get a return of type B. Otherwise, if B is a value type, the return type is a nullable wrapping around type B. So, that's a short answer to your question.
With that being said, in your case, since you're getting back a bool, it's understandable that it'll be wrapped as bool?. Knowing that, you should simply work with it as you would normally would with bool?. One way is to simply do an equality comparison to a desired value of bool.
For example:
if (Employee?.IsTerminated == true) { }
It's a bit shorter and easier to read than:
if ((Employee?.IsTerminated).GetValueOrDefault()) { }
The example comparison works, because null will never equal to a bool.
You can always use the null coalesce operator:
if (Employee?.IsTerminated ?? false) { /*do something here*/ }
With C# 6.0 in the VS2015 preview we have a new operator, ?., which can be used like this:
public class A {
string PropertyOfA { get; set; }
}
...
var a = new A();
var foo = "bar";
if(a?.PropertyOfA != foo) {
//somecode
}
What exactly does it do?
It's the null conditional operator. It basically means:
"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."
In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.
In other words, it's like this:
string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
...
}
... except that a is only evaluated once.
Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:
FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null
It can be very useful when flattening a hierarchy and/or mapping objects. Instead of:
if (Model.Model2 == null
|| Model.Model2.Model3 == null
|| Model.Model2.Model3.Model4 == null
|| Model.Model2.Model3.Model4.Name == null)
{
mapped.Name = "N/A"
}
else
{
mapped.Name = Model.Model2.Model3.Model4.Name;
}
It can be written like (same logic as above)
mapped.Name = Model.Model2?.Model3?.Model4?.Name ?? "N/A";
DotNetFiddle.Net Working Example.
(the ?? or null-coalescing operator is different than the ? or null conditional operator).
It can also be used out side of assignment operators with Action. Instead of
Action<TValue> myAction = null;
if (myAction != null)
{
myAction(TValue);
}
It can be simplified to:
myAction?.Invoke(TValue);
DotNetFiddle Example:
using System;
public class Program
{
public static void Main()
{
Action<string> consoleWrite = null;
consoleWrite?.Invoke("Test 1");
consoleWrite = (s) => Console.WriteLine(s);
consoleWrite?.Invoke("Test 2");
}
}
Result:
Test 2
Basically, I have applied ?. operator after Model as well. I am trying to know that whether it can be applied directly to the model or does it only work with the navigation properties?
The ? or null conditional operator operators on the left value, regardless of the type of value. And the compiler doesn't care what the value is on the right. It's simple compiler magic (meaning it does something you can already do, just in a simplified why).
For example
var a = model?.Value;
is the same as saying
var a = model == null ? null : model.Value;
In the second case the evaluation of checking for null has no associate with the value returned. The null conditional operator basically just always return null if the left value is null.
The type of member (Method, Field, Property, Constructor) .Value is irrelevant.
The reason your DotNetFiddle example doesn't work is because the compiler being use for the .Net 4.7.2 isn't compatible with the c# version that support the null conditional operator. Changing it to .Net 5, works:
https://dotnetfiddle.net/7EWoO5
This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.
old way to achieve the same thing was:
var functionCaller = this.member;
if (functionCaller!= null)
functionCaller.someFunction(var someParam);
and now it has been made much easier with just:
member?.someFunction(var someParam);
I strongly recommend this doc page.