Introduction
So we know a little bit about Lazy<T> now. Time to expand our knowledge a bit: let's write some code to pass a parameter to the constructor. It being the holiday season, lets involve the use of food!
Coding
Let's create a class called Food that passes a string parameter. This still uses the lazy concept to where the object doesn't exist until it really needs to. Onto some code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LazierTProject { class Program { internal class FoodExtended { private string foodID; private string aboutFood; internal FoodExtended() { } internal FoodExtended(string foodID) { this.foodID = foodID; } } public class Food { public string id; private Lazy<FoodExtended> foodExtended; public Food(string id) { this.id = id; foodExtended = new Lazy<FoodExtended>(() => new FoodExtended(this.id)); } } static void Main(string[] args) { Food turkeyForMe = new Food("Gobble gobble!"); Lazy<Food> turkeyForYou = new Lazy<Food>(() => new Food("Turkey for you")); Console.WriteLine("Turkeys declared"); Console.WriteLine(); Console.WriteLine("turkeyForYou's food initialized: {0}", turkeyForYou.IsValueCreated); Console.WriteLine(); Console.WriteLine("turkeyForMe.Message: {0}", turkeyForMe.id); Console.WriteLine("turkeyForYou.Message: {0}", turkeyForYou.Value.id); Console.WriteLine(); Console.WriteLine("turkeyForYou's food initialized: {0}", turkeyForYou.IsValueCreated); Console.WriteLine("\nPress Any Key to Exit."); Console.ReadKey(); } } }
Output
Wahoo! The coding sample works and wasn't too terrible to pass a parameter to a lazy object.
No comments:
Post a Comment