08-04-2012, 10:28 PM
(This post was last modified: 08-04-2012, 10:28 PM by AceInfinity.)
Note: The reason for this:
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.
With 4.0 this generic class essentially just allows you to allocate memory hogging objects only at the time you require them.
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.
With 4.0 this generic class essentially just allows you to allocate memory hogging objects only at the time you require them.