4 ms·
I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods. Example: let n be an int
by noblethrasher 15y ago
I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods.
Example:
let n be an int
n.Becomes("2") //returns 2
n.Becomes("sdfsd") //returns n
0.Becomes("12") returns 12
0.Becomes("sdssdf") returns 0
Non-contrived example:
var person = Person.Get(0.Becomes(Request.QueryString["id"]));
Basically, given the expression
n.Becomes(SOME_STRING)
if `SOME_STRING` can be parsed as whatever the type of `n` is then it returns the the parsed result, else it returns (the value of) `n`.
More technically, `Becomes` returns a `ParseAttemptResult<T>` that is implicitly convertible to `T`. It also has `true` and `false` operators so that it can be used in an expression expecting a `Boolean` (e.g. `if` and the ternary operator`?:`).
Github Repo: https://github.com/noblethrasher/Parser-Helpers/blob/master/ParserHelpers.cs https://github.com/noblethrasher/Parser-Helpers/blob/master/...