I was wondering if you can add something like a "null-safe"-operator in F#. I know that there might be plans for such an operator in C# for the next bigger release.
If there is no way to achieve such a behaviour, is there a way to wrap a statement that possibly could throw a NullReferenceException
into a block that catches the exception and just returns null
.
I thought of something like:
let sth = %% <@ someobject.method().another().andAnother() @>
where %%
is a custom operator that executes the expression and checks for the exception.
One Attempt I made was:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Linq.QuotationEvaluation
let (~%%) (right:Expr) =
try
right.CompileUntyped()
right()
with
| ex -> null
But this does not do what I wanted (in fact it doesn't even compile :)
I read through:
- http://msdn.microsoft.com/de-de/library/ee370577.aspx
- http://msdn.microsoft.com/de-de/library/dd233197.aspx
- and some more msdn-documentation
Does anyone have ideas how to elegantly create such a one-line try-catch for chained methods?