JumpStart # 16–Lazy Loading using Lazy<T> in C# 4.0

Before looking at the code, Read about – What is JumpStart?


From C# 4.0, .Net Framework supports Lazy initialization of instances. Lazy initialization helps in loading instances (especially useful for costly properties of objects) only when they are accessed at runtime. That means lazy properties are not loaded when actual object initialization is done.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LazyLoadingDemo {

    public class Program {

        static void Main(string[] args) {

            Console.WriteLine("Program Execution - Entry");
            Console.WriteLine("Person Object - started Creating...");

            Person P = new Person(1, "Rami");
            List<Appointment> _appointmennts;

            Console.WriteLine("Accessing Appointments of Person...Press Enter");

            _appointmennts = P.Appointments;

            Console.WriteLine("Progam Execution - Exit, Press Enter");

    public class Person {

        public int Id { get; set; }
        public string Name { get; set; }
        public List<Appointment> Appointments { get { return this._lazylstAppointments.Value; } }

        private Lazy<List<Appointment>> _lazylstAppointments;

        public Person(int _id, string _name) {
            Console.WriteLine("Id, Name of Person Initialized...");

            this.Id = _id;
            this.Name = _name;

            Console.WriteLine("Creating Lazy List of Appointments for Person Object...");

            /* Lazy List Enables you to load or instantiate properties or objects only at
             * the time of their access.
             * In the below example, when the Persons Appointments property is accessed in
             * Main, the corresponding appointments are loaded. 
            _lazylstAppointments = new Lazy<List<Appointment>>(() => GetAppointments(_id));

        private List<Appointment> GetAppointments(int _id) {

            List<Appointment> _lstAppointments = new List<Appointment>();

            Console.WriteLine("Retrieving Appointments of Person...Lazily...");
                (int i) =>
                         new Appointment() 
                             Description = String.Format("Appointment Description {0}", i.ToString()), 
                             Date = DateTime.Now 

            return _lstAppointments;

    public class Appointment {
        public string Description { get; set; }
        public DateTime Date { get; set; }





You may also like...