Use the Lazy Initialization Pattern

Problem

You have an object that contains data that’s expensive to create and might not be required.

Solution

Use the lazy initialization pattern to create or to retrieve the information "just in time."

Discussion

The lazy initialization pattern is often used with stateful objects that need to retrieve data from a database, but it can be applied to any object that’s expensive to create. The basic approach is to use a Boolean private member variable IsInitialized to track whether the object data has been retrieved yet. Here’s a basic skeleton that illustrates the concept by setting a string variable:

Public Class MyObject Private IsInitialized As Boolean = False Private _Data As String Public ReadOnly Property Data() ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.