Skip to content

Instantly share code, notes, and snippets.

@controlflow
Created September 20, 2014 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save controlflow/de10836191593eee1744 to your computer and use it in GitHub Desktop.
Save controlflow/de10836191593eee1744 to your computer and use it in GitHub Desktop.
Null propagation playground
convert "Null-conditional invocation" {
if (x != null) { // also 'cond && x != null'
x.M();
}
} into {
x?.M();
}
convert "Null-conditional invocation (inverted)" {
if (x == null) return _;
x.M();
return _; // can be implicit/void
} into {
x?.M();
return _;
}
convert "Null-conditional value return" {
if (x != null) {
return x.M();
}
return null; // maybe much upper
} into {
return x?.M();
}
convert "Null-conditional value return (inverted)" {
if (x == null) return null;
return x.M();
} into {
return x?.M();
}
convert "Null-conditional value retur (with else)" {
if (x != null) {
return x.M();
} else {
return null;
}
} into {
return x?.M();
}
convert "Null-conditional value return (inverted with else)" {
if (x == null) {
return null;
} else {
return x.M();
}
} into {
return x?.M();
}
convert "Null-conditional navigation" {
if (x != null) {
x.F();
x = x.M();
}
} into {
x?.F();
x = x?.M();
}
convert "Type-conditional invocation" {
if (x is T) {
((T) x).M();
}
} into {
(x as T)?.M();
}
convert "Type-conditional invocation (inverted)" {
if (!(x is T) return _;
((T) x).M();
return _; // can be implicit/void
} into {
(x as T)?.M();
return _;
}
convert "Nested if statements" {
if (x != null) { // also 'cond && x != null'
var y = x.M(); // optional
if (y != null && ...) { }
}
} into {
var y = x?.M();
if (y != null && ...) { }
}
convert "Merge sequential checks" {
if (x == null) return _; // also goto/continue/break
var y = x.M();
if (y == null) return _; // also goto/continue/break
} into {
var y = x?.M();
if (y == null) return _;
}
// TODO: THINK ABOUT else { } everywhere
if (liftedStatement == null) return null;
return liftedStatement;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment