c# dynamic variable with ?? and ? operator [duplicate] - c#

This question already has answers here:
What does a double question mark do in C#? [duplicate]
(7 answers)
What does question mark and dot operator ?. mean in C# 6.0?
(3 answers)
Closed 2 years ago.
Sorry for asking a simple question,
I'm new to Azure Function HTTPtriggers with C#,
Anyone know what is the name = name?? data?.name; mean in c# ?
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;

It essentially means
if name is not null
set name to name
else
if data is null
set name to null
else
set name to data.name
The second operator (?.) avoids a NullReferenceException by returning null instead of trying to use the access modifier. The first (??) returns the first operand if the value is not null, otherwise it returns the second.
Note that neither of these are specific to dynamic or Azure.
It could also have been written as
if ((name == null) && (data != null))
{
name = data.name;
}

Related

Assign if not null [duplicate]

This question already has answers here:
C# 6.0 Null Propagation Operator & Property Assignment
(3 answers)
Closed 2 years ago.
Being a fan of null-coalescing operator and the null-propagating operator, I would like to assign something if the object is not null.
Something like:
myArray.FirstOrDefault()?.Value = newValue;
Instead of:
var temp = myArray.FirstOrDefault()
if(temp != null){
temp.Value = newValue;
}
Is this possible?
(I am aware I could use SetValue() )
With C# 8.0 you can do this
temp ??= newValue;

How to avoid Tostring exception if string is null? [duplicate]

This question already has answers here:
How to do ToString for a possibly null object?
(12 answers)
Closed 4 years ago.
I want to convert the data row value to sring as follows.
userGuid = dr["user_guid"].ToString();
It may contains Guid or null(Not string empty). If it contains null i got the exception.
How can i overcome this..
I guess you are reading from data reader.
You will have to check if the value is null or DBNull and then you can call to string method.
string user_guid = dr["user_guid"] != DBNull.Value && dr["user_guid"] != null ? dr["user_guid"].ToString() : null ;
Hope this helps.
if (dr[user_guid"] != null) {
//whatever you want to do
} else {
//handle the null value in some way
}
Alternatively,
dr["user_guid"]?.ToString();
The ? is what's called a "null-safe navigator".
This might be useful, one of many ways
userGuid = dr["user_guid"]?.ToString()?? "Default Value";
Please do replace "Default Value" with whatever you feel is appropriate according to your application logic.
Maybe this:
userGuid = dr["user_guid"].ToString() ?? throw new Exception();

Application crash after detect null variable [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I have a TreeView where I want to get NextNode so I do simple like:
var nextNode = e.Node.NextNode.Text;
If it have nextNode it returns value right. Problem if it comes null, application crash and throw
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
System.Windows.Forms.TreeNode.NextNode.get returned null.
Why application crash? should not return the null variable instead application crash?
It appears that an instance of NextNode does not exist yet you attempt to access the Text property.
You have two options:
Retrieve the NextNode object and check for NULL
Use the null coalescing operator to access the text or substitute it.
1 - Check for null
NextNode node = e.Node.NextNode;
string thetext = string.Empty;
if (node != null)
thetext = node.Text
2 - Null coalescing operator
string thetext = e.Node?.NextNode?.Text ?? string.Empty;
They will both do the same thing. If NextNode is null then the variable thetext will contain an empty string, otherwise it will contain the Text of NextNode.

C# nullable check optimization [duplicate]

This question already has answers here:
Deep null checking, is there a better way?
(16 answers)
Closed 5 years ago.
Can anyone tell me how do I optimize below code.
if (report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) &&
report.Breakdown[reportName.ToString()].Result != null
)
As others have mentioned, you can use the ?. operator to combine some of your null checks. However, if you're after optimizing for performance, you should avoid the double dictionary lookup (ContainsKey and index access), going for a TryGetValue instead:
MyType match = null; // adjust type
if (report?.Breakdown?.TryGetValue(reportName.ToString(), out match) == true &&
match?.Result != null)
{
// ...
}
Ayman's answer is probably the best you can do for C# 6, for before that what you have there is pretty much the best you can do if all those objects are nullable.
The only way to optimize this further is to be checking if those objects are null before even calling the code, or better yet proofing your platform so this particular function shouldn't even be called in the first place if the values are null.
If you are just getting the value from from the dictionary however you can also simplify with the null coalescing operater '??'
Example:
MyDictionary['Key'] ?? "Default Value";
Thus if the Value at that entry is null you'll get the default instead.
So if this is just a fetch I'd just go
var foo =
report != null &&
report.Breakdown != null &&
report.Breakdown.ContainsKey(reportName.ToString()) ?
report.Breakdown[reportName.ToString()].Result ?? "Default" :
"Default";
But if you are actually doing things in the loop, then yeah you're pretty much at the best you can get there.
For C# 6 and newer, you can do it this way:
if (report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null)
You can use null conditional operator but only on C# 6
if ( report?.Breakdown?.ContainsKey(reportName.ToString()) == true &&
report.Breakdown[reportName.ToString()].Result != null )
Can you try below? Also probably better to ship it to a method.
// unless report name is already a string
string reportNameString = reportName.ToString();
if ( report?.Breakdown?.ContainsKey(reportNameString) &&
report.Breakdown[reportNameString].Result != null )
{
// rest of the code
}

Creating a custom operator - '!?' (negation of '??'). Is it possible? [duplicate]

This question already has answers here:
Is it possible to create a new operator in c#?
(7 answers)
Closed 8 years ago.
Is it possible to create a custom operator like '!?' (negation of '??') instead of writing long expression:
int? value = 1;
var newValue = value != null ? 5 : (int?)null;
I want to have:
var newValue = value !? 5;
Thanks!
No.
You cannot create your own operators in C#. You can only override (some of the) ones that already exist in the language.
You cannot define new operator in C# - the only way is to redefine existing ones, but you can not redefine ?: and ?? operators.

Categories

Resources