Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy(Of T) Usage / Initialization

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())
like image 255
lincx Avatar asked Jan 30 '13 01:01

lincx


2 Answers

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.

like image 126
Reed Copsey Avatar answered Oct 19 '22 22:10

Reed Copsey


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:

  1. Lazy(Of T) Constructor
  2. Lazy(Of T) Constructor (Func(Of T))

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")
like image 36
Neolisk Avatar answered Oct 19 '22 23:10

Neolisk