C# Anonymous Types vs Tuples with an example

 

C# Anonymous Types vs Tuples with an example

This article is the continuation of previous part 1 in which we had earlier seen how tuples reduces the code by making it more tidy and readable. But it still lacks readability when comes to add attribute in Main method which carries declarative information of Tuples. In order to overcome that we had talked about anonymous types which will discussed in this article.

Anonymous Types

Anonymous types lets us to create new type without defining them. With this way, defining read only properties can be done into a single object and not have to define type separately. Over here Anonymous Type is generating by the compiler and it is accessible only within current block code. The type of properties is also inferred or concluded by C# compiler.

Anonymous types are created by using "new" keyword in the statement together along with initializing the object.

Including Anonymous Type within existing code

For that remove existing Tuple and then create Anonymous type in it. In order to complete it follow below written steps: -

  1. Under "PData" function first remove Tuple keyword and its datatype then write typecast "object". Here we are using typecast object because exposing anonymous type object outside "PData" function is not allowed. So with the help of typecast we are exposing anonymous type outside.
  2. static object PData(string strngData)

  3. Create a proper static typecast function which will take the object and return back generic type casted object to Main method.
  4. static T Cast(object obj, T type)
            {
    return (T)obj;  
            }
    
  5. Create anonymous type here with new keyword and within braces do the mapping of student data properties to array.
  6. return new {SchoolName = ArrayData[0], StudentName = ArrayData[1], RollNo = Convert.ToInt32(ArrayData[2])};
  7. Declare variable name "StudentData" and do casting with keyword "Cast" which has object "PData" in Main method with type as "new" having "SchoolName", "StudentName", "RollNo". State properties as below
  8. varStudentData = Cast(PData(strng), new {SchoolName="", StudentName="", RollNo=0 } );
  9. Now on console line if you go and check you will find attributes of "StudentsData" exactly as it was declared. It is not showing as Item1, Item2 and so onů which was seen while using Tuple. Here all the three attributes are correctly seen as shown below: -
  10. Console.WriteLine("School Name:" + StudentData.SchoolName);

    Console.WriteLine("Student Name:" + StudentData.StudentName);

    Console.WriteLine("Roll No.:" + StudentData.RollNo.ToString());

For "RollNo" just convert it to string using "ToString()". Rest all lines of code keep it as it is.

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

namespace ConsoleApplication5
{
classProgram
    {
staticvoid Main(string[] args)
        {
stringstrng = "St.GeorgeHighSchoolBannie 20";

varStudentData = Cast(PData(strng), new {SchoolName="", StudentName="", RollNo=0 } );
Console.WriteLine("School Name:" + StudentData.SchoolName);
Console.WriteLine("Student Name:" + StudentData.StudentName);
Console.WriteLine("Roll No.:" + StudentData.RollNo.ToString());
Console.ReadLine();
        }

staticobjectPData(stringstrngData)
        {
string[] ArrayData = newstring[2];
ArrayData = strngData.Split(' ');
returnnew {SchoolName = ArrayData[0], StudentName = ArrayData[1], RollNo = Convert.ToInt32(ArrayData[2])};

        }

staticT Cast(objectobj, T type)
        {
return (T)obj;  
        }
    }
}

Now we are finished with the coding part now go click "Rebuild" in order to rebuild our existing solution. Finally click "ctrl+F5" on the keyboard and get to see the final result which we were expecting. Result are going to be same as we had got while using Tuple. But the important thing is that we have improved code readability more with the use of Anonymous Type.

We have improved of our existing complex code to make it tidier using Tuple in part 1. But still code was lacking readability which we have improved in this part 2 of the article with Anonymous Type. Hope that reading this part 1 and part 2 of the article found to be useful to you.

Also see if are looking for project covering video series right from the scratch, do click on YouTube as shared below: -

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Nov
28
2016

Tuples in c# example step by step

CLICK TO READ FULL ARTICLE

Views - 2928 |Category - C#

Nov
22
2016

Anonymous Methods in C# with an example Step by Step

CLICK TO READ FULL ARTICLE

Views - 4125 |Category - C#

Oct
30
2014

Understand Monitor vs Mutex vs Semaphore vs SemaphoreSlim - Onlinebuff

CLICK TO READ FULL ARTICLE

Views - 19893 |Category - C#

Oct
18
2014

Thread Pooling in C#.NET with real time example - Onlinebuff

CLICK TO READ FULL ARTICLE

Views - 16752 |Category - C#

Oct
06
2014

Step by Step Partial Classes and Partial Methods in C#.NET with example

CLICK TO READ FULL ARTICLE

Views - 9174 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

8ouhr