Suppose I want to check a bunch of objects to make sure none is null:
if (obj != null &&
obj.Parameters != null &&
obj.Parameters.UserSet
You could use reflections if you don't mind losing static type safety. I do mind, so I just use your first short-circuiting construction. A feature like Eric mentioned would be welcome :)
I've thought about this problem a few times. Lisp has macros that solve the problem in the way you mentioned, since they allow you to customize your evaluation.
I have also tried using extension methods to solve this problem, but nothing there is less ugly than the original code.
Edit: (Replies don't let me insert code blocks, so editing my post)
Oops, didn't keep up on this. Sorry about that :)
You can use reflections to look up and evaluate a member or property via a string. A class one of my friends wrote took a syntax like:
new ReflectionHelper(obj)["Parameters"]["UserSettings"]
It worked via method chaining, returning a ReflectionHelper at each level. I know that NullReferenceException is a problem in that example. I just wanted to demonstrate how evaluation can be deferred to runtime.
An example slightly closer to being helpful:
public class Something
{
public static object ResultOrDefault(object baseObject, params string[] chainedFields)
{
// ...
}
}
Again, this syntax stinks. But this demonstrates using strings + reflections to defer evaluation to runtime.