Skip to content

Instantly share code, notes, and snippets.

@aashishkoirala
Last active August 29, 2015 13:57
Show Gist options
  • Save aashishkoirala/9356316 to your computer and use it in GitHub Desktop.
Save aashishkoirala/9356316 to your computer and use it in GitHub Desktop.
// Example 1: Dictionaries.
// Using "string" as key/value for example; could be anything.
IDictionary<string, string> myDictionary;
// ...
// ...
// Returns Perhaps<string>.NotThere if not found.
var dictionaryResult = myDictionary.LookFor("MyKey");
if (dictionaryResult.IsThere)
{
// Throws if called on "NotThere".
var string1 = dictionaryResult.Value;
var string2 = dictionaryResult.ValueOrDefault;
// Automatically casts to underlying type.
var string3 = dictionaryResult + " and so on and so forth.";
// Other stuff to do if the value is there.
}
// Look for stuff and operate on it in one sequence of calls.
myDictionary.LookFor("MyKey").DoIfThere(value => /* Do stuff with value */);
// Look for stuff and get otehr stuff based on it in one sequence of calls.
var finalValue = myDictionary
.LookFor("MyKey")
.DoIfThere(value => /* Return stuff based on value */, "Default value");
// Example 2: Parsing text.
string text;
// ...
text.ParseInteger().DoIfThere(value => /* Do stuff with value */);
text.ParseDateTime().DoIfThere(value => /* Do stuff with value */);
// and so on and so forth for long, float, double, decimal, bool
// Example 3: Stuff that throws ("int" used as type for example, could be anything).
var result = Perhaps<int>.Try(() => /* Stuff that may throw an exception. */);
if (!result.HasError)
{
// Do stuff here. Now, this may seem weird, but this makes more sense when you think of
// getting a list of results and filtering out errored ones and then operating further on
// valid ones, etc.
}
// Example 4: LINQ stuff ("string" used as type for example, could be anything).
IEnumerable<string> list;
// ...
var first = list.PerhapsFirst(x => x.ParseInteger().IsThere); // Aaha!
var single = list.PerhapsSingle().DoIfThere(x => /* Do stuff with value */);
var last = list.PerhapsLast(x => x.StartsWith("ABC"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment