lincx lincx - 1 year ago 127 Question

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())

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download