Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Created April 20, 2015 12:15
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 JakobOvrum/7e3a7bc130ab7db28de3 to your computer and use it in GitHub Desktop.
Save JakobOvrum/7e3a7bc130ab7db28de3 to your computer and use it in GitHub Desktop.
Approximation of C#'s Null Propagation Operator in D
class Foo
{
string name;
this(string name)
{
this.name = name;
}
}
class Bar
{
Foo foo;
this(Foo foo)
{
this.foo = foo;
}
}
class Baz
{
Bar bar;
this(Bar bar)
{
this.bar = bar;
}
}
template getOrNull(string op, ops...)
{
auto getOrNull(T)(T obj)
{
auto result = __traits(getMember, obj, op);
static if(ops.length)
{
return result is null? null : .getOrNull!ops(result);
}
else
return result;
}
}
unittest
{
auto threeDeep = new Baz(new Bar(new Foo("foobar")));
assert(threeDeep.getOrNull!("bar", "foo", "name") == "foobar");
auto nullCases = [
new Baz(new Bar(new Foo(null))),
new Baz(new Bar(null)),
new Baz(null)
];
foreach(nullCase; nullCases)
assert(nullCase.getOrNull!("bar", "foo", "name") is null);
assert(nullCases[0].getOrNull!("bar", "foo") !is null);
assert(nullCases[1].getOrNull!("bar") !is null);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment