Shortcut for "Null If Object Is Null, or Object.Member If Object Is Not Null"

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:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
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

  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about
    0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('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



Leave a reply



Submit