Assign if not null [duplicate] - c#

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;

Related

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

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;
}

why would a ? appear in IEnumerable<int>?.ToList()? [duplicate]

This question already has answers here:
What does x?.y?.z mean?
(3 answers)
Closed 6 years ago.
I was reviewing some code and I came across the following line of code:
List authorIntList = authorIds?.ToList();
In the example above, authorIds is an IEnumerable. What is the purpose of the ? in the line of code above? I'm not sure I've ever seen this pattern before. What does it do and in which version of .NET was it implemented?
That's called the "null conditional operator" -- i.e. ? and . together -- new to C# 6.0. What it means is that, if authorIds is not null, then it will call/return ToList() on it. Otherwise, it will return null. It's basically syntactic sugar so you don't have to write lengthier code like List AuthorIntList = authorIds != null ? authorIds.ToList() : null;.
The "Null Conditional Operator" exists as a way to shorthand "If this isn't null, do the thing, otherwise return null". It's basically the same as
List authorIntList = authorIds ? authorIDs.ToList() : null; //null coalescing
or
List authorIntList = null;
if(authorIDs != null) { authorIntList = authorIDs.ToList(); } //traditional if
It is a null conditional operator that in many languages people call it Elvis operator. It has been added from c# 6.0 and checks your code with null.
So if you have something like:
var x= a?.b?.c?.d;
x will be null if any of a,b,c or d be null. and it will be the value in d if all of them are not null. before you had to put them in if conditions.
if(a!= null && a.b!= null && a.b.c!= null)
{
x= a?.b?.c?.d;
}
Correction Null Conditional operator
https://msdn.microsoft.com/en-us/library/dn986595.aspx
It's like saying if authorId's is not null then execute ToList() else returns null.

Calling functions in C# ternary operator [duplicate]

This question already has answers here:
C# Conditional Operator Not a Statement?
(9 answers)
Closed 6 years ago.
Why is this code not valid? Pretty sure it's legit in C /C++
Pseudocode:
String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") : Console.WriteLine("bar");
The ternary operator is used to return values and those values must be assigned.
If you want to invoke void methods in a ternary operator, you can use delegates like this:
String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();
console.writeline return void.. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression
MSDN
As discussed here, in C#, not every expression can be used as a statement.

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.

C# code won't compile. No implicit conversion between null and int [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?
Why doesn't this work? Seems like valid code.
string cert = ddCovCert.SelectedValue;
int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
Display(x);
How should I code this? The method takes a Nullable. If the drop down has a string selected I need to parse that into an int otherwise I want to pass null to the method.
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
I've come across the same thing ... I usually just cast the null to (int?)
int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);

Categories

Resources