Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A
dotnetinter

.NET interview questions: - Explain how anonymous Types are better than Tuples?

Anonymous Type: - Anonymous Types help us to create an object without
declaring its data type and also help us to create properties with good
meaningful names. Since the name of the data type is not specified that the type
is referred to as an Anonymous Type.

Tuples: - In simple words Tuple are nothing but they are objects which helps
us to logically group other kind of objects inside.

A Tuple is a data structure that has a specific number and sequence of
elements. An example of a tuple is a data structure with three elements (known
as a 3-tuple or triple) that are used to store an identifier such as a person's
name in the first element, a year in the second element, and the person's income
for that year in the third element. The .NET Framework directly supports tuples
with one to seven elements. In addition, you can create tuples of eight or more
elements by nesting tuple objects in the Rest property of a Tuple

[Error: Irreparable invalid markup ('<t1,>') in entry. Owner must fix manually. Raw contents below.]

<p><b>Anonymous Type</b>: - Anonymous Types help us to create an object without
declaring its data type and also help us to create properties with good
meaningful names. Since the name of the data type is not specified that the type
is referred to as an Anonymous Type.

<b>Tuples</b>: - In simple words Tuple are nothing but they are objects which helps
us to logically group other kind of objects inside.

A <b>Tuple</b> is a data structure that has a specific number and sequence of
elements. An example of a tuple is a data structure with three elements (known
as a 3-tuple or triple) that are used to store an identifier such as a person&#39;s
name in the first element, a year in the second element, and the person&#39;s income
for that year in the third element. The .NET Framework directly supports tuples
with one to seven elements. In addition, you can create tuples of eight or more
elements by nesting tuple objects in the Rest property of a <b>Tuple</b><t1, br="">T3, T4, T5, T6, T7, TRest&gt; object.

Let&rsquo;s first see in what kind of scenario we will use &ldquo;</t1,><b>Tuples</b>&rdquo; and &ldquo;<b>Anonymous
Types</b>&rdquo;.

Suppose we have a simple string which has Customer&rsquo;s, FirstName, MiddleName,
LastName and PhoneNumber like below code snippet.</p>
<pre>
string str = &quot;Feroz S Shaikh 966457&quot;; // Here you can see that the Customer&#39;s Name and
Phone Number are Seperated by (&lsquo; &rsquo;)spaces.</pre>

<p>Now, you would like to parse the data and take the data in to individual
variables like below code snippet.</p>
<pre>
string strFirstName = &quot;&quot;;//this variable will hold Customer FirstName.
string strMiddleName = &quot;&quot;;//this variable will hold Customer MiddleName.
string strLastName = &quot;&quot;;//this variable will hold Customer LastName.
double PhoneNumber = 0;//this variable will hold Customer PhoneNumber.</pre>

<p>In order to parse data into individual variables, we have to create a
function with &ldquo;Out&rdquo; parameters and have to use &ldquo;Split&rdquo; function like below code
snippet.</p>
<pre>
static void ParseData(string strData, out string strFirstName, out string strMiddleName,
out string strLastName, out double PhoneNumber)
{
string[] ArrayData = new string[3];//Created Array with Size 3.
ArrayData = strData.Split(&#39; &#39;);//Used Split function to split the data.

strFirstName = ArrayData[0];//Passed the data to strFirstName.
strMiddleName = ArrayData[1];//Passed the data to strMiddleName.
strLastName = ArrayData[2];//Passed the data to strLastName.
PhoneNumber = Convert.ToDouble(ArrayData[3]);//Passed the data to PhoneNumber.
}</pre>

<p>Still now we have done with parsing the data.

Now just invoke this function from the main class like below code snippet.</p>
<pre>
ParseData(str, out strFirstName, out strMiddleName, out strLastName, out PhoneNumber);</pre>

<p>Now, let just display the result for that just add the below code snippet.</p>
<pre>
Console.WriteLine(&quot;FirstName :&quot; + strFirstName);
Console.WriteLine(&quot;MiddleName : &quot; + strMiddleName);
Console.WriteLine(&quot;LastName : &quot; + strLastName);
Console.WriteLine(&quot;PhoneNumber : &quot; + PhoneNumber.ToString());
Console.ReadLine();</pre>

<p>Let&rsquo;s see how the result set look like.</p><p><img alt="" border="0" height="72" src="http://pics.livejournal.com/dotnetinter/pic/0004dk85" width="432" />


Now, the above code is nice its work&rsquo;s properly but the concern here is the code
tidiness, in current scenario all the variables are individual variables in case
if you want to parse the data around it would be very tedious job to do and it
would make your very lengthy and not be very easy to read.

The solution for the above code is that if you can club the individual variables
all together in to an object and use that object to pass the data anywhere you
want to that would bring down our code to a great extent.


So <b>Tuples</b> and <b>Anonymous Types</b> help us out to achieve the above
solution and make our code more readable and understandable.

Now, we will first see how exactly <b>Tuples</b> help in above scenario and what
is the drawback of using <b>Tuples</b> in the above scenario and later we will
see how Anonymous Types helps us to make your code better than using Tuples.

So, let see how Tuples helps to make code better in the above scenario.

<b>Step1</b>: - create a new project Console Application for that Go To &gt; New &gt;
File &gt; Project &gt; Windows &gt; Select Console Application.</p>
<p><img alt="" border="0" height="140" src="http://pics.livejournal.com/dotnetinter/pic/0004ee85" width="628" /></p>
<p><img alt="" border="0" height="41" src="http://pics.livejournal.com/dotnetinter/pic/0004f768" width="523" />



<b>Step2</b>: - create a string variable containing data like below code snippet.</p>
<pre>
string str = &quot;Feroz S Shaikh 966457&quot;;</pre>

<p><b>Step3</b>: - creating tuple like below code snippet.</p>
<pre>
static Tuple<string, double=""> ParseData(string strData)
//created tuple with three string data type and one double type.

{
string[] ArrayData = new string[3];//Created Array with Size 3.
ArrayData = strData.Split(&#39; &#39;);//Used Split function to split the data.
//assigned the data to the tuple object.
return Tuple.Create<string, double="">
(ArrayData[0],
ArrayData[1],
ArrayData[2],
Convert.ToDouble(ArrayData[3]));
}</string,></string,></pre>

<p><b>Step4</b>: - Now receive the tuple in the main class like below code snippet and also display data.</p>
<pre>
var CustomerInformation = ParseData(str);//recieved the tuple.
//assigned the tuple data.
Console.WriteLine(&quot;FirstName :&quot; + CustomerInformation.Item1);
Console.WriteLine(&quot;MiddleName : &quot; + CustomerInformation.Item2);
Console.WriteLine(&quot;LastName : &quot; + CustomerInformation.Item3);
Console.WriteLine(&quot;PhoneNumber : &quot; + CustomerInformation.Item4);
Console.ReadLine();</pre>

<p>In the above code snippet as soon as you click CustomerInformation(.)(dot)
the VS business intelligence will show like below diagram.


<img alt="" border="0" height="178" src="http://pics.livejournal.com/dotnetinter/pic/0004gcds" width="518" />



Now just run your application and will see the result like below diagram.


<img alt="" border="0" height="72" src="http://pics.livejournal.com/dotnetinter/pic/0004dk85" width="432" />


Now, let see what the negative point of using Tuples is.</p><p><img alt="" border="0" height="178" src="http://pics.livejournal.com/dotnetinter/pic/0004gcds" width="518" />


In above diagram you can see that there is no way to identify that Item1
represent the FirstName, Item2 represent the MiddleName, Item3 represent the
LastName and Item4 represent the PhoneNumber. So clearly in terms of writing a
maintainable code this is not desirable.

If somehow we can change this Item1, Item2, Item3 and Item4 in to good
meaningful properties name like FirstName, MiddleName, LastName and PhoneNumber
than it would be much easy to understand the code in better manner. In this kind
of scenario Anonymous Types help us out.

Let&rsquo;s see how exactly Anonymous Type help to solve the above problem for that
you just need to follow the following steps.


<b>Step1</b>: - create a new project Console Application for that Go To &gt; New &gt;
File &gt; Project &gt; Windows &gt; Select Console Application.</p>
<p><img alt="" border="0" height="140" src="http://pics.livejournal.com/dotnetinter/pic/0004ee85" width="628" /></p>
<p><img alt="" border="0" height="41" src="http://pics.livejournal.com/dotnetinter/pic/0004f768" width="523" />



<b>Step2:</b> - create a string variable containing data like below code snippet.</p>
<pre>
string str = &quot;Feroz S Shaikh 966457&quot;;</pre>

<p><b>Step3</b>: - create an Anonymous Type like below code snippet.</p><p></p>
<pre>
static object ParseData(string strData)
{
string[] ArrayData = new string[3];//Created Array with Size 3.
ArrayData = strData.Split(&#39; &#39;);//Used Split function to split the data.
//Creating Anonymous Types on the fly.
return new {
FirstName = ArrayData[0],
MiddleName = ArrayData[1],
LastName = ArrayData[2],
PhoneNumber = Convert.ToDouble(ArrayData[3])};
}</pre>
<p></p><p>In the above code snippet you can see that we have created an Anonymous Type with FirstName, MiddleName, LastName, PhoneNumber and this is getting type&nbsp; casted to object because we cannot return Anonymous Type object outside the&nbsp; function straight forward. We need to type caste it like below code snippet.</p>
<pre>
static T Cast<t>(object obj, T type)
{
return (T)obj;
}</t></pre>

<p>Step4: - Now receive Anonymous Type in the main class like below code snippet
and also display data.</p><p></p>
<pre>
var CustomerInformation = Cast(ParseData(str),new {FirstName=&quot;&quot;,MiddleName=&quot;&quot;,
LastName=&quot;&quot;,PhoneNumber=0});
//assigned the data.
Console.WriteLine(&quot;FirstName :&quot; + CustomerInformation.FirstName);
Console.WriteLine(&quot;MiddleName : &quot; + CustomerInformation.MiddleName);
Console.WriteLine(&quot;LastName : &quot; + CustomerInformation.LastName);
Console.WriteLine(&quot;PhoneNumber : &quot; + CustomerInformation.PhoneNumber);
Console.ReadLine();</pre>

<p>In the above code snippet as soon as you type CustomerInformation(.)(dot) the
VS business intelligence will show properties like below diagram.



<img alt="" border="0" height="179" src="http://pics.livejournal.com/dotnetinter/pic/0004hqww" width="461" />

Now, in the above diagram you can clearly see that Item1, Item2, Item3 and Item4
is now being completely replaced by good meaningful property names like
FirstName, MiddleName, LastName and PhoneNumber which become much easier to read
and understand the code.


Now just run your application and will see the result like below diagram.



<img alt="" border="0" height="72" src="http://pics.livejournal.com/dotnetinter/pic/0004dk85" width="432" />


Following view the video on &ldquo;Why anonymous types are better than tuples?&rdquo;</p><p>
<a href="http://youtu.be/fW9tJgErO7E?hd=1" target="_blank"><img alt="" border="0" height="397" src="http://pics.livejournal.com/dotnetinter/pic/0004k1gh" width="640" /></a>


&nbsp;Also see our tutorials on <a href="http://www.questpond.com/" target="_blank">interview questions and answers for .NET</a>


Regards,


View more author&rsquo;s blog o <a href="http://dotnetinterviewquestions.blog.co.in/2011/08/18/net-interview-questions-steps-showing-anonymous-types-are-better-than-tuples/" target="_blank">Most asked .NET interview questions</a></p>
Tags: .net and c# interview questions, .net and c# training, .net interview questions and answers, anonymous types, csharp interview questions, information technology questions, programming interview questions, tuples
Subscribe

  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 0 comments