88 questions
1
vote
2
answers
128
views
Null Coalescing Operator not working in Powershell 7
Param(
[String] $foo
)
$foo ??= "bar" # does not work
$foo = $foo ?? "bar" # does not work
$foo = $foo ? $foo : "bar" # works
write-host $foo
I am using Powershell ...
0
votes
0
answers
32
views
Why does curr1?.val ?? 0 + curr2?.val ?? 0 return 2 instead of 7? [duplicate]
I try to add two values of nullable items. I noticed that expression returns 2 instead of expected 7, but I would like to understand why.
Code:
public class ListNode
{
public int val;
public ...
0
votes
0
answers
28
views
Declaring an empty delegate vs Null Conditional [duplicate]
In my opinion, the fewer conditionals and checks I need to do, the better.
When I use C# a common pattern for me is declaring events something like this:
public event Action MyEvent = delegate { };
...
0
votes
1
answer
56
views
The proper use of using the `?.` while searching array with LINQ?
So I have this code:
foreach (var user in ServersHolder.Servers.Find(f => f.ID == 9999).Online.FindAll(g => g.LoginPhase == 3))
{
await trySendPacket(9999, user.GUID.ToString(), OpCode....
1
vote
1
answer
75
views
null-conditional, null-coalescing, enumerable and params keyword
I didn't know what better title to chose for the question as I don't know what's the problem. Consider the following small C# code:
static void Main(string[] args)
{
F1(null);
}
public static void ...
3
votes
1
answer
153
views
Why using null-conditional operator in nullable context breaks static analyzer?
Why after using null-conditional-operator in nullable context (#nullable enable
) the static analyzer shows CS8602 warning?
var test = new List<int>();
Console.WriteLine(test.Count); // Ok
...
1
vote
0
answers
68
views
Whats the differece between Item[n]?.MinValue and Item[n].MinValue? [duplicate]
I would like to add MapWinGis to my C# application ,but I don't know the following:
Whats the difference between (examples 1 and 2)
and the meaning of the [question mark] in the first sample?
...
1
vote
1
answer
124
views
Effect of null conditional operator in comparison with default
I am wondering about the behavioral difference that can be seen in output for Test 2 on example below.
I'm on .NET Core 3.1 for this scenario.
using System;
public class Program
{
...
0
votes
2
answers
231
views
Using null conditional operator("?.") with "function that returns a bool value"
using System;
public class A{
public bool func(){
return true;
}
public int func2(){
return 10;
}
}
public class HelloWorld
{
public static void Main(string[...
0
votes
1
answer
690
views
Is there a performance difference between null-check and null-conditional-operator in C#?
I am wondering whether there is a difference in performance between these two if-statements:
if(myObject != null && myObject.someBoolean)
{
// do something
}
if (myObject?.someBoolean ?? ...
1
vote
1
answer
90
views
Is it possible to use a null-conditional operator to set a Func<> to null?
Let's imagine the following situation:
public class A
{
private readonly Func<bool> _myFunction;
...
public A(Func<bool> myFunction)
{
_myFunction = myFunction ?? ...
1
vote
3
answers
122
views
Are function parameters evaluated in a C# null-conditional function call?
Are function arguments always evaluated in a C# null-conditional function call?
i.e. in the following code:
obj?.foo(bar());
Is bar evaluated if obj is null?
1
vote
1
answer
468
views
How to Skip Null Objects returned from CimInstance
Get-CimInstance -ComputerName $pc -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $compare } | Remove-CimInstance
Because some system profiles have empty values for ...
2
votes
1
answer
323
views
Is there a shorter way to write this in C# 8?
if (value2 != null)
{
value1 = value2;
}
? and ?? operators don't seem to be useful here. I thought of using the ternary operator.
value1 = (value2 != null) ? value2 : value1;
...
0
votes
2
answers
480
views
Why is the .NET null conditional operator not returning false when trying to check if a collection has any items?
I'm trying to do the following check:
if (result?.Pets?.Any() == false) { ... }
and if result == null .. then it's not going inside the scope of that if check.
I thought that result?. will (in this ...
1
vote
1
answer
369
views
Error CS0165 Use of unassigned local variable 'json'
I am trying to get value from the HttpContext with a key Correlation-Context, but I am not sure why I am getting the error while trying to use the variable json.
internal static CorrelationContext ...
4
votes
2
answers
1k
views
How to use null conditional operator in a dynamic JSON with JsonConvert.DeserializeObject
I'm using Newtonsoft to deserialize an known JSON object and retrieve some values from it if they're present.
The crux is there is that object structure may keep changing so I'm using dynamic to ...
0
votes
2
answers
413
views
C# Is there a way to put a Null-conditional operator (?) on T?
I have an interface<T>. This interface has a method Compare(T x, T y).
x can never be null.
y has a large chance of being null.
I want to make this clear by using the Null-conditional operator ...
1
vote
2
answers
7k
views
C# Null Conditional in Ternary condition
Am refactoring some old code and see something in the following format:
Type = rec["IsFlagged"]?.ToString() == "True" ? "Yes" : "No"
which should not work if ...
0
votes
2
answers
191
views
Why use null conditional operator when a variable that can't be null?
I saw the below code from MSDN:
using System;
public sealed class Foo : IDisposable
{
private readonly IDisposable _bar;
public Foo()
{
_bar = new Bar();
}
public void ...
4
votes
2
answers
829
views
C# 6.0 null-conditional operator in if statements
Can someone please explain the logic of the null-conditional operator in if statements?
Imagine the following code
List<string> items = null;
if (items?.Count == 0)
{
Console.WriteLine("...
0
votes
1
answer
477
views
What is the point of the null-condition operator in PowerShell?
PowerShell 7 recently moved out of the experimental stage the Null-conditional (?.) operator. In playing around with it a bit and reading the examples in the link above I think I understand how it ...
1
vote
0
answers
426
views
Set an object's property conditional on the object not being null
This works, calling Invoke only if the member is not null:
List<Command> list = GetCommands();
list.FirstOrDefault(predicate)?.Invoke();
Conditionally calling a property setter does not work:
...
0
votes
1
answer
541
views
Why is the null conditional operator not allowed for property assignment? [duplicate]
I just noticed that property assignment is not allowed in combination with the null conditional operator.
With methods is it not a problem at all though.
I always thought that properties are just ...
0
votes
2
answers
452
views
Is there a null-conditional operator for array concatenation?
const addendum = null
const acts.change = [act1];
console.log( acts.change.concat(addendum?.changedActions) );
Outputs [act1, null] rather than the expected [act1]. Am I misusing the null-conditional ...
1
vote
1
answer
130
views
A strange question about Null-conditional?
env: VS2017 v15.9.24, .net framework 2.0 c# console project.
this is a very simple console project, no any reference, all codes are in program.cs:
namespace ConsoleApp1
{
class Program
{
...
2
votes
1
answer
580
views
Why doesn't Visual Studio warn me about a null reference exception?
I wonder why Visual Studio 2019 doesn’t complain about this piece of C# code:
dynamic deserializedBody = JsonConvert.DeserializeObject(requestBody);
deserializedBody?.date.ToString();
Since ...
1
vote
1
answer
250
views
Why does the null-conditional operator promote thread-safety in C#?
There's a modern idiom in C# that utilizes the null-conditional operator to promote thread-safety when using delegates. Namely:
Update?.Invoke(this, theArgs);
Why does this work? Does the C# ...
0
votes
0
answers
497
views
C# Race-Condition and Null-Conditional Operator in Object/Method-Chaining Method Calls
I know this is asked in various situations, but I didn't find this exact question, or satisfying answers, sorry, if I wasn't enough cautious.
Symptoms:
When having nested objects, Like Class A ...
1
vote
3
answers
654
views
Is there any Null-Conditional Operator like for Events.. Button?.Click +=(ss,ee)
Why there's no Null-Conditional Operator for events ?
For example i have following code which raise event if object is not null :
Button TargetButton = null;
if(IsRunning)
{
...
12
votes
3
answers
6k
views
Null Conditional in Powershell?
C# and other languages have null-conditionals usually ?.
A?.B?.Do($C);
Will not error out when A or B are null.
How do I achieve something similar in powershell, what's a nicer way to do:
if ($A) {
...
0
votes
1
answer
368
views
Correct use of null-conditional operator in LINQ while reading XML
I have following XML file that I am parsing using XML serializer.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Projects>
<Global>
<Variables>
...
-1
votes
2
answers
679
views
Null Conditional Operator should used until what? ?.ToString()?.Trim() etc [duplicate]
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 ...
3
votes
3
answers
573
views
Null conditional and ToString together give unexpected results
I have 2 statements that use the null conditional (?) operator and perform ToString on the result. These 2 statement seem like they should have the same result, but they do not. The only different is ...
2
votes
4
answers
632
views
Does the null-conditional operator function the same with delegates and regular objects?
Reference
I'm currently dealing with some thread sensitive code.
In my code I have a list of objects that is manipulated by two different threads. One thread can add objects to this list, while the ...
4
votes
2
answers
346
views
Why does the null-conditional operator change regular property access?
I'm confused about how the null-conditional operator cascades with normal property access. Take these two examples:
a?.b.c
(a?.b).c
I would expect them to be equivalent: first, the value of a?.b is ...
4
votes
2
answers
2k
views
UnassignedReferenceException even though using the null-conditional operator
I'm getting a UnassignedReferenceException: The variable _Preset of Foo has not been assigned. even though I'm using the null-conditional operator ?..
My code:
// […]
myTarget.Preset?.ApplyTo(...
0
votes
1
answer
829
views
C# Null Conditional Operator inside method argument
I have following methods:
float myMethod(MyObject[][] myList)
{
float a = 0;
if (myListProcessingMethod(myList?.Where(x => x.mySatisfiedCondition()).ToList()))
{
a = ...
5
votes
3
answers
555
views
C# null-conditional shorthand for method arguments
The null-conditional operator is very useful when the method belongs to the object in question, but what if the object in question is an argument? For example, can this be shortened?
var someList = ...
-3
votes
1
answer
61
views
Why we don't need to use string? str and for decimal or int we need to use decimal? price = p?price
I'm new in c#. I have a confusion in null conditional operator.
in case of string everyone using this line
string name = p?.name;
but in case of decimal or float
decimal? price = p?.price;
int? ...
8
votes
2
answers
1k
views
Why can I omit the subsequent null-conditional operators in an invocation chain?
Consider the following code:
IEnumerable<int> xx = null;
var tt = xx?.Where(x => x > 2).Select(x => x.ToString());
It assigns null to tt.
The question is: why does it work properly?
I ...
1
vote
4
answers
16k
views
Use null-conditional operator to set value to 0 if null
I'm new to C# but not to programming in general.
I am trying to set add some error checking to my program. There are 3 textboxes and I am trying to make it so that if the text box is left blank, it ...
0
votes
1
answer
83
views
Does null conditional operator always break on first null ocurrence?
Having a C# background, I always use the ?. operator when acessing class properties (when using Entity Framework relationships).
For example, if I use this and the status class is null, it'll throw ...
5
votes
1
answer
470
views
Negating the null conditional operator returns unexpected results for nothing
We encountered unexpected behavior with the null conditional operator if the variable value is Nothing.
The behavior of the following code keeps us a bit confused
Dim l As List(Of Object) = ...
21
votes
3
answers
10k
views
Using the Null Conditional Operator to check values on objects which might be null
I've been playing with C# 6's Null Conditional Operator (more info here).
I really like the syntax and I think it makes the code much more readable however I think it is questionable as to what ...
15
votes
1
answer
14k
views
Using null-conditional bool? in if statement [duplicate]
Why this code works:
if (list?.Any() == true)
but this code doesn't:
if (list?.Any())
saying Error CS0266 Cannot implicitly convert type 'bool?' to 'bool'
So why is it not a language feature making ...
8
votes
2
answers
586
views
When the null conditional operator short-circuits, does it still evaluate method arguments?
The null conditional operator can be used to skip method calls on a null target. Would the method arguments be evaluated or not in that case?
For example:
myObject?.DoSomething(GetFromNetwork());
Is ...
4
votes
4
answers
282
views
?. operator in C# not compiling for unknown reason
In the following code, one of the two variants does not compile:
class C
{
public decimal DecimalField;
}
static C GetC() { return new C(); } //Can return null in reality.
C c = GetC(); //Get a ...
8
votes
4
answers
6k
views
Null-conditional boolean in if statement
I have an event which returns a boolean. To make sure the event is only fired if anyone is listening, i call it using the null-conditional operator (questionmark).
However, this means that I have to ...
4
votes
4
answers
1k
views
Null-Conditional Operator
var a = b?.c.d;
Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding ...