code_junkie

Implementing a “LazyProperty” class - is this a good idea?

Nov 13th, 2011
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. if (backingField == null)
  2. backingField = SomeOperation();
  3. return backingField;
  4.  
  5. public class LazyProperty<T>
  6. {
  7. private readonly Func<T> getter;
  8.  
  9. public LazyProperty(Func<T> getter)
  10. {
  11. this.getter = getter;
  12. }
  13.  
  14. private bool loaded = false;
  15. private T propertyValue;
  16.  
  17. public T Value
  18. {
  19. get
  20. {
  21. if (!loaded)
  22. {
  23. propertyValue = getter();
  24. loaded = true;
  25. }
  26. return propertyValue;
  27. }
  28. }
  29.  
  30. public static implicit operator T(LazyProperty<T> rhs)
  31. {
  32. return rhs.Value;
  33. }
  34. }
  35.  
  36. first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
  37.  
  38. public HeavyObject First { get { return first; } }
  39.  
  40. private LazyProperty<HeavyObject> first =
  41. new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
  42. public HeavyObject First {
  43. get {
  44. return first;
  45. }
  46. }
  47.  
  48. private HeavyObject first;
  49. public HeavyObject First {
  50. get {
  51. if (first == null) first = new HeavyObject { MyProperty = Value };
  52. return first;
  53. }
  54. }
  55.  
  56. public Type Value
  57. {
  58. get
  59. {
  60. if(ViewState["key"] == null)
  61. ViewState["key"] = someDefaultValue;
  62. return (Type)ViewState["key"];
  63. }
  64. set{ ViewState["key"] = value; }
  65. }
Add Comment
Please, Sign In to add comment