I'm trying to figure out whats the difference between this two usage of Lazy and which is the more appropriate to use, or is it just the same?
Dim context As New Lazy(Of DbContext)
Dim context As Lazy(Of DbContext) = New Lazy(Of DbContext)(Function() New DbContext())
If the lambda is doing nothing but constructing an instance using the default constructor, the effect is the same, as the constructor for Lazy<T>
without a delegate just uses the type's default constructor. In that case, I'd use your first option.
The reason for the second option, however, is that you sometimes need more information to construct your object. For example, this would be legal and function correctly:
Dim instance = New Lazy(Of SomeType)(Function() New SomeType("Foo"))
Note that here we're using a non-default constructor for SomeType
.
This statement
Dim context As Lazy(Of DbContext) = New Lazy(Of DbContext)(Function() New DbContext())
is functionally equivalent to this:
Dim context As New Lazy(Of DbContext)(Function() New DbContext())
So we are down to usage of these two constructors of Lazy class:
According to MSDN, for (1):
When lazy initialization occurs, the default constructor of the target type is used.
For (2):
When lazy initialization occurs, the specified initialization function is used.
So if creating an object using default constructor works for you, pick (1), otherwise (2). Note that you can use non-default constructor of T, or even constructors of parent types, so this would also work (String
inherits from Object
):
Dim obj As New Lazy(Of Object)(Function() "123")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With