Skip to content

Instantly share code, notes, and snippets.

@joeriks
Last active December 18, 2015 02:18
Show Gist options
  • Select an option

  • Save joeriks/5709550 to your computer and use it in GitHub Desktop.

Select an option

Save joeriks/5709550 to your computer and use it in GitHub Desktop.
Return named and typed "tuples" from funcs (within same main funcion) and easy encapsulate small pieces of logic, like in javascript.
// say we are in a function and like to encapsulate some logic easily, then return a typed object
// we can do that with anonymous object:
// (you cannot return anonymous type from a Func without the helpers afaik)
// also worth noting: anonymous types are immutable
var returnNamedTuples = Fn.Invoke(()=>{
var value = 123;
var isHigh = value>100;
return new {value,isHigh};
});
if (returnNamedTuples.isHigh) ...
// can use this to create small functions aswell:
var splitName = Fn.Create((string x)=>{
var lastSpace = x.LastIndexOf(' ');
var first = (lastSpace !=-1)?x.Substring(0,lastSpace ):"";
var second = (lastSpace !=-1)?x.Substring(lastSpace +1):"";
return new {first, second};
});
var name = splitName("Mr. Foo Bar");
var result = String.Format("Hello {0} I know your last name is {1}",name.first, name.second);
public static class Fn
{
public static TOut Invoke<TOut>(Func<TOut> func)
{
return func();
}
public static Func<TOut> Create<TOut>(Func<TOut> func)
{
return func;
}
public static TOut Invoke<TIn, TOut>(Func<TIn, TOut> func, TIn t1)
{
return Create(func)(t1);
}
public static Func<TIn, TOut> Create<TIn, TOut>(Func<TIn, TOut> func)
{
return func;
}
public static Func<T1, T2, TOut> Create<T1, T2, TOut>(Func<T1, T2, TOut> func)
{
return func;
}
public static Func<T1, T2, T3, TOut> Create<T1, T2, T3, TOut>(Func<T1, T2, T3, TOut> func)
{
return func;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment