Tuple – Replacement to temporary Entity classes.

C# 4.0 has introduced Tuple to replace entity classes which we create for temporary purpose to store values when returning from any methods. In general practice, we create entity class containing some properties in it to store values which lets say we store from DAL to return to presentation layer. These classes sometimes are for temporary use and of no use except storing values. Tuple, is really useful to replace such classes. Examples of it are as below:

static void Main(string[] args)
{
            //var t = Tuple.Create<string, int>("Vishal", 29);
            //var t = Tuple.Create("Vishal", 29, new Tuple<string, string>("Rajkot","Gujarat"));

            //It will give compilation error, as Tuple.Create method can only create upto 8 elements.
            //var t = Tuple.Create(1,2,3,4,5,6,7,8,9);

            //It will work because new Tuple<> can create 8 or more elements.
            //var t = Tuple.Create(1, 2, 3, 4, 5, 6, 7, new Tuple<int, int>(8, 9));
            //Console.WriteLine(t);

            //It can access with Item1, Item2, t.Rest.Item1.Item2, etc.
            var t = Tuple.Create(1, 2, 3, 4, 5, 6, 7, new Tuple<int, int>(8, 9));
            Console.WriteLine(t.Rest.Item1.Item2);

            //Console.WriteLine(t);
            Console.Read();
}

 
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.