Using / initializing lazy (Of T)

I'm trying to figure out what is the difference between these two uses of Lazy and which one is more appropriate to use, or is it the same thing?

Dim context As New Lazy(Of DbContext)

Dim context As Lazy(Of DbContext) = New Lazy(Of DbContext)(Function() New DbContext())

      

+3


source to share


2 answers


If the lambda does nothing but construct an instance using the default constructor, the effect is the same as the constructor for Lazy<T>

no delegate, it just uses the default constructor. In this case, I would use your first option.

The reason for the second option, however, is that you sometimes need additional information to create your object. For example, this will legal and work correctly:



Dim instance = New Lazy(Of SomeType)(Function() New SomeType("Foo"))

      

Note that we are using a different constructor here from the default SomeType

.

+2


source


This statement

Dim context As Lazy(Of DbContext) = New Lazy(Of DbContext)(Function() New DbContext())

      

functionally equivalent to this:

Dim context As New Lazy(Of DbContext)(Function() New DbContext())

      

So, we are moving away from using these two Lazy class constructors :



According to MSDN, for (1):

When lazy initialization is performed, the default constructor for the target type is used.

For (2):

When lazy initialization is performed, the specified initialization function is used.

So, if an object using the default constructor works for you, select (1), otherwise (2). Note that you can use a non-default constructor for T, or even constructors of parent types, so this will work as well ( String

inherits from Object

):

Dim obj As New Lazy(Of Object)(Function() "123")

      

+1


source







All Articles