Tuple in C# 4.0

Tuple is a new class introduced in C# 4.0. Tuple basically provides way to group the items of different data types. A static Tuple class provides 8 overloads of create method to create Tuple of size 1 to 8. Also using new keyword and nesting tuples you can create more sized Tuple. Now for example tuple created with 3 elements called 3-tuple or triple that can hold three elements of any type. So first element may be firstname that is string, second element may be phone number that is int and salary which is double may be the third element. And we can read those values using item property of tuple like for 3-tuple it will tuple.Item1, tuple.Item2 and tuple.Item3.

Tuple example 3-tuple

     var tuple3 = new Tuple("Johan", 1234567890, 56000.90);
     Console.WriteLine(tuple3.Item1);
     Console.WriteLine(tuple3.Item2);
     Console.WriteLine(tuple3.Item3);

In above example it will print
Output:
  Johan
  1234567890
  56000.90

Lazy loading C#. Lazy initialization.

C# 4.0 introduced new class Lazy which provided for Lazy initialization. Lazy instantiation here means object is not created until it is get used first time. Primary use of Lazy initialization is performance improvements, reduce program memory requirements.Lazy provides thread safe object initialization.

Lasy<T> example to load object lazily

public partial class LazyClass : System.Web.UI.Page 
{
 private Lazy<List<string>> lazyItems = null; 
 public LazyClass() 
 { 
   lazyItems = new Lazy<List<string>>(GetItems); 
 } 
 public List<string> GetItems() 
 {
      List<string> items = new List<string>(); 
      for (int i = 0; i < 10; i++) 
       { 
          items.Add(string.Format("Item {0}", i)); 
       } return items;
 }

 public List<string> GetItemValues { get { return lazyItems.Value; } } 
}

So in above example we have defined private Lazy<List<string>> lazyItems = null; and then in constructor we have delegate the call to GetItems method which will return list of items. But here it will not generate and return list until we call "lazyItems.Value".