Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[C#] Lazy Initialization Test (Lazy<T>)
#2
Note: The reason for this:
Code:
new Lazy<MyClass>(() => { return new MyClass(); });

What we're doing here is using the optional param which expects a generic delegate of type System.Func<>, which is why you see a lambda expression, and what we are doing here is pointing to a method (through the lambda), which returns the same type created by the Lazy<T>; the MyClass object. Remember that when you create a class, what you're really doing is creating an object, because classes are derived from System.Object as with every other type either directly or indirectly.

Here's the problem, when we create the Lazy<T> variable, we're invoking the default constructor for MyClass, so the trick i've done here is chained that default constructor to a 'master constructor' which accepts 2 params, of type int, and string. Smile

With 4.0 this generic class essentially just allows you to allocate memory hogging objects only at the time you require them.
Reply


Messages In This Thread
RE: [C#] Lazy Initialization Test (Lazy<T>) - by AceInfinity - 08-04-2012, 10:28 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)