Questions tagged [null-coalescing]
The concept of setting a default value if a condition evaluates to null.
59
questions
0
votes
2answers
79 views
Using c# NULL coalescing operator with NOT NULL Scenarios
I am populating a Class using LINQ and LinkUrl is a string property of my class.I need to set a value only if a property is not null , other wise no need to assign any values
Currently The conditional ...
0
votes
0answers
31 views
Why does (Guid?)null ?? default return empty guid [duplicate]
Output from VS Immediate Window
default(Guid?)
=> null
(Guid?)null == default
=> true
(Guid?)null ?? default
=> {00000000-0000-0000-0000-000000000000}
I expected the last to be null and not ...
1
vote
3answers
78 views
How to print the null values if the dictionary has it using LINQ
I have dictionary with the following keys and values. I am trying to print the dictionary, but nothing prints where there is a null value. How do I print "null" in the output?
Dictionary<...
1
vote
2answers
38 views
Null coalescing string and conditional string via logical OR-operator results in number
Null coalescing by ORing a string (via PRIORITIES[NUM_TO_PRIORITY[priorityNum]] where priorityNum is input) and a string (via conditional Object.values(PRIORITIES).includes(priorityNum) ? priorityNum :...
7
votes
1answer
1k views
None propagation in Python chained attribute access [duplicate]
Is there a null propagation operator ("null-aware member access" operator) in Python so I could write something like
var = object?.children?.grandchildren?.property
as in C#, VB.NET and TypeScript, ...
88
votes
3answers
6k views
What is the ?[]? syntax in C#?
While I was studying the delegate which is actually an abstract class in Delegate.cs, I saw the following method in which I don't understand
Why the return value uses ? though it's already a ...
0
votes
2answers
58 views
Is the c# coalescence the same as an if statement when setting to null?
Are these two statements the same?
if (dep.BirthDate.HasValue) {
myObj.GetType().GetProperty("birthdate").SetValue(myObj, (DateTime)dep.BirthDate, null);
}
myObj.GetType().GetProperty("birthdate")....
1
vote
2answers
891 views
How to configure CRA with TS to support nullish-coalescing-operator
So i started a new CRA project and I'm using the TS beta to get some sweet features like the chaining operator, but i also want to use nullish-coalescing-operator ifExists ?? elseUseThis
...
0
votes
0answers
34 views
is this equivalent ? (int) listofobj?.Count() to (listofobj == null)?0:listofobj.Count();
i have
List<someobjects> listOfObj;
i have some property where i'd like to return number of objects
i tried it like
get => (int)listOfObj?.Count();
but app crashes with System....
2
votes
0answers
64 views
How can I use a coalesce operator in a DRY way; when assigned value is null, keep own value
I am sending value in object orderContract which will replace values of entity if contract value is not null but if contract property is null it will retain its own value.
Currently I have used ...
6
votes
3answers
417 views
Multi-argument null coalesce and built-in “or” function in Python
Python has a great syntax for null coalescing:
c = a or b
This sets c to a if a is not False, None, empty, or 0, otherwise c is set to b.
(Yes, technically this is not null coalescing, it's more ...
-1
votes
1answer
92 views
Which is more efficient for initialising a property, null checking in an if or coalescence?
I have been working to make some code more efficient, and I am wondering now which pattern is the more efficient. The solution has code in both VB.NET and C# for legacy reasons.
I have put in the VB ...
11
votes
5answers
12k views
c# shorthand for if not null then assign value
Is there any shorthand in c# now that will cutdown the following code:
var testVar1 = checkObject();
if (testVar1 != null)
{
testVar2 = testVar1;
}
In this situation only want to assign ...
3
votes
2answers
879 views
?? or .GetValueOrDefault()
I have properties type int? and decimal? that are being used in a calculation. If the value of any of them is null it has to default to 0. I'm trying to decide between using null-coalescing or ...
0
votes
3answers
729 views
How to efficiently display text instead of null when binding in vue.js?
In the following code site can be null, but if it is there, then company will not be null. How can I efficiently display a "-" when the site is null that scales well for 1000's of these rows?
<tr ...
1
vote
5answers
85 views
Incrementing not existing element of array without notice
I want to increment a value of an array, which is potentially not existing yet.
$array = [];
$array['nonExistentYet']++; // Notice
Problem
This leads to a NOTICE.
Attempt
I found a way to do this,...
8
votes
2answers
448 views
Null-coalescing out parameter gives unexpected warning
Using this construct:
var dict = new Dictionary<int, string>();
var result = (dict?.TryGetValue(1, out var value) ?? false) ? value : "Default";
I get an error saying CS0165 use of unassigned ...
0
votes
1answer
114 views
Missing Dart null checking shorthand?
I know that Dart has the null checking shorthands
x = y ?? z;
and
x = y?.z;
But what if I have a statement like
x = (y != null) ? SomeClass(y) : z;
I don't want to pass null to the SomeClass ...
2
votes
2answers
583 views
How to use null-coalescing operator with ActionResult ASP.NET Core 2.1
Can someone explain me why I'm getting an error on the null-coalescing on the following method:
private readonly Product[] products = new Product[];
[HttpGet("{id}")]
public ActionResult<Product&...
2
votes
1answer
2k views
Null coalescing on a dict entry in python
So, I'm aware that, in Python I can do this:
variable_name = other_variable or 'something else'
...and that that will assign 'something else' to variable_name if other_variable is falsy, and ...
4
votes
1answer
166 views
Unwrap/coalesce a multi-level optional
I'm trying to write a function to unwrap optionals with an arbitrary number of levels of nesting. Here's the test I'm using:
let a: Int??? = 1
let b: Int??? = nil
print(a.unwrap(0), b.unwrap(0)) // ...
6
votes
2answers
390 views
Null coalescing operator (??) with return
I was wondering why it is possible to do this in C# 7.0:
int? test = 0;
int test2 = test ?? throw new Exception("Error");
..but not this:
int? test = 0;
int test2 = test ?? return;
Can someone ...
-1
votes
4answers
115 views
?? Operator (C#) for double returns incorrect result
Using C#, any idea why the following method returns 57.999999999999993 (instead of 58)?
double Test_Null_Coalescing_Operator()
{
double? x = 0.58;
return ((x ?? 0) * 100);
}
//returns 57....
1
vote
1answer
160 views
Null-coalescing operator in conjuction with JObject
I have below code written to read JArray from a given JObject.
To my understanding, when the value of "tags" in JObject is null, IEnumerable should be initialized as empty.
IEnumerable<string> ...
0
votes
1answer
43 views
empty text input means empty $_POST[] element? (Null coallesce)
So my question is:
If I don't write anything in an input
<input type="text" name="test">
in a simple form with post method, when I receive the $_POST array in my action url, the $_POST["test"]...
1
vote
3answers
439 views
Optional chaining and coalescing incl. function arguments
Optional chaining lets us make decisions on the existence of objects:
var text : String?
let len = text?.lengthOfBytes(using: .utf8) ?? 0
Which will always set len to an integer.
Is something ...
1
vote
1answer
348 views
PHP 5 login “syntax error, unexpected '?' ” while using ?? operator
This code is part of the login form, and I want to make sure that the field is not blank. When I am using this line of code I get the following error:
syntax error, unexpected '?'
if(is_blank($...
4
votes
2answers
231 views
C# type inference (“var”) assignment from '??' null-coalescing operator
I've read many of the SO questions on the null coalescing ?? operator but none of them seem to address the following specific issue, which concerns neither nullability (here), operator precedence (...
-2
votes
1answer
2k views
Ternary assignment without “else” expression [duplicate]
Is it possible to use a shorthand for ternary assignment expressions of the type
boolean x = false;
// ... code ...
a = x ? b : a; // Assigning a to a is pointless
a += x ? 1 : 0; // Adding 0 to ...
7
votes
2answers
2k views
null-conditional operator doesn't work with Func<T> inside a generic method
Is this a compiler bug or is there a specific chosen reason why the null-conditional operator doesn't work with Func inside of generic methods?
To give an example the following doesn't compile
...
62
votes
11answers
5k views
Is there a shorthand way to return values that might be null?
How can I write a shorthand of the following scenario?
get
{
if (_rows == null)
{
_rows = new List<Row>();
}
return _rows;
}
5
votes
2answers
20k views
ORACLE SQL: How do I replace NULL with 0 in a Pivot function
How can I replace NULL with 0 in a PIVOT function on ORACLE SQL?
This is the query I'm trying to write:
SELECT *
FROM
(
SELECT DISTINCT
CUSTOMER_ID AS CUSTOMER_ID,
CASE
WHEN ...
2
votes
3answers
840 views
How to correctly do Nil Coalescing in Swift?
Supposed to do like this
var inputField = UITextField()
let defaultText = "PLACEHOLDER"
let newText = inputField.text!.isEmpty ? defaultText : inputField.text!
let newText2 = inputField.text ?? ...
2
votes
3answers
100 views
How to translate “var a = collection?.First()?.somePropA ?? new A();”
What is the purpose of single question mark on the right side of assignment in expression with null-coalescing operator? Example:
var a = collection?.First()?.somePropA ?? new A();
5
votes
4answers
13k views
C# Null coalesce with LINQ
I have 2 classes which looks like this:
class Widget
{
string Selected { get; set; }
List<Option> Options { get; set; }
}
class Option
{
string InternalCode { get; set; }
...
1
vote
2answers
161 views
Access Optional property in multiple function for calculations - Swift
I have a NSObject Subclass. Say CityWalks
class CityWalks{
var totalCount:Int?
}
How do I use this property further? Should I check the nil coalescing every time this value is accessed.
...
5
votes
1answer
234 views
Is the .NET Reflector unable to reflect over the null-coalescing operator correctly?
I wrote this piece of code:
private Queue<int> EnsureQueue()
{
return _queue ?? (_queue = new Queue<int>(10));
}
and the reflector gives me:
private Queue<int> EnsureQueue()
{
...
3
votes
3answers
62 views
Non-repetitive way of saying: access this object's member unless the object is null [duplicate]
Let's say I have a set of cars, where each car has a steering wheel. I'd like to write a line of code that looks for a car in the set and returns its steering wheel, or returns null if the car isn't ...
5
votes
1answer
698 views
How to code an intelligent coalesce in Java?
object.getProperty().getSubProperty().getSubSubProperty();
Consider the code above. An object has a property, that has a subProperty, that has a subSubProperty, that can be accessed with getter ...
0
votes
1answer
113 views
Operating on undefined variable - null coalescing
function add(num) {
var sum;
for (var i = 1; i < num + 1; i++){
sum = (sum || 0) + i;
};
return sum;
}
add(9);
What is a keyword to describe the behavior for defining sum when ...
0
votes
2answers
653 views
nil coalescing: Using optional types as default value in Swift
I have this:
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue, {
if let data = NSURLConnection.sendSynchronousRequest(self....
3
votes
2answers
713 views
Is there an equivalent of isset or a null coalescing operator in SASS?
I want to set a variable only if it hasn't been set.
SO...
In _layout.scss:
$page-width: 1100px;
However, in my _module.scss file, I don't want to have a dependency on _layout.scss
I'd like to ...
2
votes
2answers
131 views
Null Coalesce with colors
protected override void OnEnter(EventArgs e)
{
// this.Font = new Font(this.Font, FontStyle.Italic);
base.BackColor = _colors.SelectedBackColor ?? base.BackColor;
base....
0
votes
2answers
7k views
SQL Server convert NULL to empty string in select *
I need to execute the following:
SELECT * FROM [MY_TVF](9186)
FOR XML AUTO, ELEMENTS
And replace all NULL values with an empty string '' to include them in the XML. I know I can spit out the ...
0
votes
3answers
142 views
How to concat strings with space delimiter where each string is nullable?
I have a table with multiple nullable string fields.
For reporting I would like to combine them into a single string that is delimited with a space for every field. The right side must be trimmed.
...
2
votes
2answers
965 views
Why doesn't the null coalescing operator work on my nullable int when I convert it to a string?
At first I tried to write an If-Then-Else statement using a ternary operator.
It works fine then Just out of curiosity I decided to write the same code using a
null-coalescing operator but it doesn'...
4
votes
2answers
217 views
Is there a way to implement and make use of a “NOT null coalescing” operator?
Is there a not null coalescing operator in C# which in case could be used such as:
public void Foo(string arg1)
{
Bar b = arg1 !?? Bar.Parse(arg1);
}
The following case made me think of it:
...
4
votes
2answers
740 views
How to use collasce null operator with DbNull.Value?
Well this is one of method to handle DBNull.value,
But I want a syntax using null-coalescing operator to handle DBNull.value
This will work
decimal UnitPrice = row["UnitPrice"] == DBNull.Value ? 0....
26
votes
3answers
4k views
Null Coalescing Operator in F#?
When interacting with C# libraries, I find myself wanting C#'s null coalescing operator both for Nullable structs and reference types.
Is it possible to approximate this in F# with a single ...
4
votes
3answers
25k views
Sending null parameters to Sql Server
I have a SqlCommand object that I'm using to update a database table but it doesn't interpret my null values correctly.
Here is the SQL:
UPDATE dbo.tbl
SET param1 = @param1,
param2 = @param2,
...