Shortcut for null if object is null, or object.member if object is not null
There's no short form for that; implementing one is a fairly frequently requested feature. The syntax could be something like:
x = foo.?bar.?baz;
That is, x is null if foo or foo.bar are null, and the result of foo.bar.baz if none of them are null.
We considered it for C# 4 but it did not make it anywhere near the top of the priority list. We'll keep it in mind for hypothetical future versions of the language.
UPDATE: C# 6 will have this feature. See http://roslyn.codeplex.com/discussions/540883 for a discussion of the design considerations.
Looking for shorthand to insert a variable into object if not null
I'm afraid there's no real shorter way of doing this (well technically a minor one and then somewhat more obtuse one)
I tried playing around with the nullish operator
??
, but I have to say the working solution seems uglier than what I'm a bout to propose.Essentially it boils down to the fact, you're looking for the negation of the nullish operator (or alternatively a nullish ternary), neither of which sadly exist (yet).
Here's a relatively compact solution, which just improves upon your solution and simplifies it with the usage of the &&
logical AND short-circuit operator
const notNullish = (value) =>
value !== null && typeof value !== 'undefined'
const foo = (a, b) => ({
...(notNullish(a) && {a}),
...(notNullish(b) && {b}),
})
console.log('foo(6, 7) =>', foo(6, 2))
console.log('foo(6) =>', foo(6))
console.log('foo() =>', foo())
console.log('foo(0, false) =>', foo(0, false))
c# shorthand for if not null then assign value
There are a couple!
The ternary operator:
testvar2 = testVar1 != null ? testvar1 : testvar2;
Would be exactly the same logic.
Or, as commented you can use the null coalescing operator:
testVar2 = testVar1 ?? testVar2
(although now that's been commented as well)
Or a third option: Write a method once and use it how you like:
public static class CheckIt
{
public static void SetWhenNotNull(string mightBeNull,ref string notNullable)
{
if (mightBeNull != null)
{
notNullable = mightBeNull;
}
}
}
And call it:
CheckIt.SetWhenNotNull(test1, ref test2);
NULL safe object checking in JAVA 8
You can chain all of those calls via Optional::map
. I sort of find this easier to read than if/else
, but it might be just me
Optional.ofNullable(person.getClothes())
.map(Clothes::getCountry)
.map(Country::getCapital)
.ifPresent(...)
Is there a shortcut to execute something only if its not null?
In Java 8:
static <T> boolean notNull(Supplier<T> getter, Predicate<T> tester) {
T x = getter.get();
return x != null && tester.test(x);
}
if (notNull(something::getThatObject, MyObject::someBooleanFunction)) {
...
}
If this style is new to the readers, one should keep in mind, that full functional programming is a bit nicer.
throwing an exception if an object is null
I don't know why you would..
public Exception GetException(object instance)
{
return (instance == null) ? new ArgumentNullException() : new ArgumentException();
}
public void Main()
{
object something = null;
throw GetException(something);
}
How to check for an undefined or null variable in JavaScript?
You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You'll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo;
if (foo) //evaluates to false because foo === undefined
Undefined properties , like
someExistingObj.someUndefProperty
. An undefined property doesn't yield an error and simply returnsundefined
, which, when converted to a boolean, evaluates tofalse
. So, if you don't care about0
andfalse
, usingif(obj.undefProp)
is ok. There's a common idiom based on this fact:value = obj.prop || defaultValue
which means "if
obj
has the propertyprop
, assign it tovalue
, otherwise assign the default valuedefautValue
".Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
in
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue
C# elegant way to check if a property's property is null
In C# 6 you can use the Null Conditional Operator. So the original test will be:
int? value = objectA?.PropertyA?.PropertyB?.PropertyC;
Related Topics
ASP.NET Urlencode Ampersand for Use in Query String
Cannot Access Non-Static Field
Visual Studio 2015 Not Syntax Highlighting Razor Nor Intellisense
C# Iterating Through an Enum? (Indexing a System.Array)
How to Pass a Username/Password in the Header to a Soap Wcf Service
Asp .Net MVC Disable Client Side Validation at Per-Field Level
Ref and Out Parameters in C# and Cannot Be Marked as Variant
Programmatically Add New Column to Datagridview
Is SQLcommand.Dispose() Required If Associated SQLconnection Will Be Disposed
Datatrigger Does Not Change Text Property
Should I Always Return Ienumerable<T> Instead of Ilist<T>
Checking If a String Array Contains a Value, and If So, Getting Its Position
Using JSON.Net to Return Actionresult