Null Conditional Operator should used until what? ?.ToString()?.Trim() etc [duplicate] - c#

This question already has answers here:
Why can I omit the subsequent null-conditional operators in an invocation chain?
(2 answers)
Closed 3 years ago.
I have misunderstanding some of Null-conditional operator ?. mechanism
Example getting Length of String variable
object variable = null;
int? Length = variable?.ToString()?.Trim()?.Length;
Should we using ?. operator in all cascading properties of members of object we need test ?
The variable object is null so testing with null-conditional operator should be for ToString() method only or cascading members of ToString() ?
This
?.ToString()?.Trim()?.Length
OR
?.ToString().Trim().Length
I though that if ToString is null there's no need for test next member after it.

The null-conditional operator is just syntactic sugar for a null-check. So the following two codes are similar:
object variable = null;
int? Length = variable?.ToString()?.Trim()?.Length;
VS:
object variable = null;
int? Length;
if(variable != null)
{
var a = variable.ToString()?;
if(a != null)
{
var result = a.Trim();
if(result != null)
Length = result.Length;
}
}
So depending on if the member can even return null- e.g. ToStringmay while Trim does not - you may have to check for it using ?.
In your example you can omit the check for Trim, but not for ToString.

Well, null conditional operator returns either null or some class; since int is a struct you can't put
// Doesn't compile. What is Length when variable == null?
int Length = variable?.ToString()?.Trim()?.Length;
but either use Nullable<int>
// Now Length can be null if variable is null
int? Length = variable?.ToString()?.Trim()?.Length;
or turn null into reasonable int:
// in case variable is null let Length be -1
int Length = variable?.ToString()?.Trim()?.Length ?? -1;
Since null.ToString() throws exception then ?. in variable?.ToString() is mandatory; all the other ?. are optional if we assume that ToString() and Trim() never return null.
if variable is null then ?. will immediately returns null
if variable is not null, both .ToString() and .Trim() will not return null and the check ?. is redundant.
So you can put either
int? Length = variable?.ToString().Trim().Length;
Or
int Length = variable?.ToString().Trim().Length ?? -1;

Related

Checking if a List is Null before getting Count results in -> Cannot implicitly convert type 'int?' to 'int

I'm trying to find the number of items present in a list.In order to prevent the null exception.I'm using the ? operator to check whether myBenchmarkMappings is null before getting its count.
int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings?.Count;
But this results in Cannot implicitly convert type 'int?' to 'int'. exception
What am i doing wrong ?
This is because the ? operator will return the value or null. And you can't assign null to int.
You have two options. First is to mark the int as nullable.
But in this case latter you will need to check if the int is null.
int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;
if (benchmarkAccountCount == null)
{
// null handling
}
The second option, which I think is better, you can user the null-coalescing operator ?? and give the benchmarkAccountCount a default value in case the list is null.
int benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count ?? 0;
When .myBenchmarkMappings is null, then .myBenchmarkMappings?.Count is also null. This means this code could possibly assign a null to an int, but an int can't store a null. Change the type to int? if you want to accommodate an int or null.
int? benchmarkAccountCount = portfolioWrapper.myBenchmarkMappings?.Count;
You can try to use ?: operator to check if list is null:
int benchmarkAccountCount =portfolioWrapper.myBenchmarkMappings!=null ? portfolioWrapper.myBenchmarkMappings.Count:0;

How to test an object for null in an elegant way in C#?

I want to test if the Output.ScriptPubKey.Addresses array is null or not and then assign it to a parameter list. If it's null then I want to set the parameter value to 0, else use the number of items in the array.
What I've written below feels clumsy and verbose, is there a more elegant way?
int addressCount;
if (Output.ScriptPubKey.Addresses == null) { addressCount = 0; } else {
addressCount = Output.ScriptPubKey.Addresses.Length;
}
var op = new DynamicParameters();
op.Add("#AddressCount", addressCount);
The code used to be:
op.Add("#AddressCount", Output.ScriptPubKey.Addresses.Length);
but sometimes the Addresses array is empty.
You want the null-coalescing operator combined with the null conditional operator:
int addressCount = Output.ScriptPubKey.Addresses?.Length ?? 0;
The left-hand-side of the ?? operator will be used unless the result is null, in which case it will use 0. The ?. evaluates against null and if any part of (a potential chain) evaluates to null, all of it evalutes to null. Thus it short-circuits and allows you to compose expressions such as this.

Null-conditional operator and !=

With the introduction of Null-Conditional Operators in C#, for the following evaluation,
if (instance != null && instance.Val != 0)
If I rewrite it this way,
if (instance?.Val != 0)
it will be evaluated to true if instance is a null reference; It behaves like
if (instance == null || instance.Val != 0)
So what is the right way to rewrite the evaluation using this new syntax?
Edit:
instance is a field of a big object which is deserialized from JSON. There are quite a few pieces of code like this, first check if the field is in the JSON, if it is, check if the Val property does NOT equal to a constant, only both conditions are true, do some operation.
The code itself can be refactored to make the logical flow more "making sense" as indicated by Peter in his comment, though in this question I am interested in how to use null-conditional operators with !=.
With Null-Conditional operator returned value can always be null
if ((instance?.Val ?? 0) != 0)
If instance was null, then instance?.Val will also be null (probably int? in your case). So you should always check for nulls before comparing with anything:
if ((instance?.Val ?? 0) != 0)
This means:
If instance?.Val is null (because instance is null) then return 0. Otherwise return instance.Val. Next compare this value with 0 (is not equal to).
You could make use of null coallescing operator:
instance?.Val ?? 0
When instance is null or instance is not null but Val is, the above expression would evaluate to 0. Otherwise the value of Val would be returned.
if ((instance?.Val).GetValueOrDefault() != 0)
the ? conditional operator will automatically treat the .Val property as a Nullable.

Is there a conditional operator for setting a variable in C# to the value of another variable if the latter isn't null?

Something like the ternary operator (?:) or the null coalescing operator (??). It seems silly to me to take up two lines and be so wordy when the other operators exist.
EDIT:
Since it's requested, here's two possible examples of what I hope that I can find
var variable ?= mightBeNull;
or
var variable = mightBeNull != null ? mightBeNull
Really, it's either something that can be used to assign a value, if it's not null, to a variable or an If without an Else packaged nicely in an operator.
The ??= operator is coming to C# 8.
int? i = null; // i = null
i ??= 0; // i = 0
i ??= 1; // i = 0
// different ways of writing 'i ??= 0;':
i = i ?? 0;
if (i == null) i = 0;
So you want this?
if (other != null)
someVariable = other;
You could do the following, but I'd argue that the above is better due to clarity and possible side effects:
someVariable = other ?? someVariable;
The above might cause side effects if someVariable is a property and either the get or set can cause side effects; this shouldn't be important if your property follows the ordinary guidelines. Or, as Servy points out, even if it's a field, it could created different semantics in a multithreaded app. I should note that in the first example, you read other twice, which also has the potential for complexity to enter (though a smaller potential than the latter example).
I bet this is what you are looking for.
Let's say we have a function, myFunction that says whether the argument passed input is null or not. If input is null, it will return "Input is null!", else it will return "Input is not null".
This is the normal approach:
public String myFunction(string input) {
if (input == null)
return "Input is null!";
else
return "Input is not null";
}
And this is the other approach (What you are looking for):
public String myFunction(string input) {
return (input == null) ? "Input is null!" : "Input is not null";
}
It is called (?: conditional operator).
To assign a value to a variable only if it is not null, you would need to use an if. Neither the conditinal nor the null coalesce operators would do that.
if(somethingElse != null) something = somethingElse;
There is no specific operator in C# that does exactly this.
In Visual Studio 2015 C# there is a new operator called the Null-Conditional that does what you are asking. It is the ?. or ? operator.
int? length = customers?.Length; // null if customers is null
Customer first = customers?[0]; // null if customers is null
int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null
Currently useable in previous versions of C# but not an operator but rather a one liner would be to use the ? : statement
?: operator
condition ? first_expression : second_expression;
AssingningTO = (someVar == null) ? null: someVar; // if null assign null ELSE assign someVar
AssingningTO = (someVar == null) ? String.Empth(): someVar; // if null assign empty string else someVar
Nullable types can represent all the values of an underlying type, and an additional null value.
http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

What does ?? mean in C#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What do two question marks together mean in C#?
What does the ?? mean in this C# statement?
int availableUnits = unitsInStock ?? 0;
if (unitsInStock != null)
availableUnits = unitsInStock;
else
availableUnits = 0;
This is the null coalescing operator. It translates to: availableUnits equals unitsInStock unless unitsInStock equals null, in which case availableUnits equals 0.
It is used to change nullable types into value types.
The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
?? Operator (C# Reference)
according to MSDN, The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
Check out
http://msdn.microsoft.com/en-us/library/ms173224.aspx
it means the availableUnits variable will be == unitsInStock unless unitsInStock == 0, in which case availableUnits is null.

Categories

Resources