code_junkie

C# - How do I define an inline method Func<T> as a parameter?

Nov 11th, 2011
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.55 KB | None | 0 0
  1. public static T GetItem<T>(string key, Func<T> defaultValue)
  2. {
  3. if (HttpContext.Current.Session[key] == null)
  4. {
  5. HttpContext.Current.Session[key] = defaultValue.Invoke();
  6. }
  7. return (T)HttpContext.Current.Session[key];
  8. }
  9.  
  10. Foo foo = GetItem<Foo>("abc", () => new Foo("blah"));
  11.  
  12. return ((T)HttpContext.Current.Session[key]) ?? defaultValue();
  13.  
  14. public static T GetItem<T>(string key)
  15. where T : new()
  16. {
  17. return ((T)HttpContext.Current.Session[key]) ?? new T();
  18. }
  19.  
  20. var log = SessionItem.GetItem("logger", () => NullLog.Instance)
Add Comment
Please, Sign In to add comment