Click here to Skip to main content
15,861,168 members
Articles / Programming Languages / C#

Return Anonymous type

Rate me:
Please Sign up or sign in to vote.
4.19/5 (20 votes)
25 Oct 2012CPOL2 min read 56.2K   18   15
Return Anonymous type
In this Article I am going to discuss about returning the anonymous type and how to handle in code. Following is list of fact about anonymous type.  

Quick facts about Anonymous type
  • Anonymous types are reference type derived form system.objects.
  • Properties of the Anonymous type is read only.
  • If two Anonymous type has same properties and same order than compiler treats its as same type. But if both are in one assembly.
  • Anonymous type has method scope. If you want to return Anonymous type form the method than you have to convert it in object type. But is not good practice.
You can read more on blog about this: Anonymous types
As in about facts you cannot return anonymous type from the method , if you want to return you need to cast it in object.
Now in following post I am going to do same return the anonymous type as object and going to show three different way to handle it.
  • Way 1: Handle using Dynamic type 
  • Way 2: Handle by creating same anonymous type 
  • Way 3: Handle using Reflection
To Understand each way I created following method which returns anonymous type
object AnonymousReturn()
{
     return new { Name = "Pranay", EmailID = "pranayamr@gmail.com" }; 
}
Way 1: Handle using Dynamic type
dynamic newtype= AnonymousReturn();
Console.WriteLine(newtype.Name + "  " + newtype.EmailID);
As you see in above example first line of code calling method which is returning anonymous type as object and assign the return value to dynamic type. Second line of code just printing the property value of anonymous type.
Note : No intellisense support as we are using dynamic type. And need to remember the property name and type also.

Way 2: Handle by creating same anonymous type
object o = AnonymousReturn();
var obj = Cast(o, new { Name = "", EmailID = "" });
Console.WriteLine(obj.Name + "  " + obj.EmailID);
In this way return value of the anonymous type is get assigned to object. Next line of the code cast object to the same anonymous type. To accomplish this task following method does casting of object.
T Cast<T>(object obj, T type) { return (T)obj; }
This done song type conversation and provide intelligence support.

Way 3: Handle using Reflection
object refobj = AnonymousReturn();
Type type = refobj.GetType(); 
PropertyInfo[] fields = type.GetProperties(); 
foreach (var field in fields) 
{
   string name = field.Name; 
   var temp = field.GetValue(obj, null);
   Console.WriteLine(name + "  " + temp);
}
This way making use of reflection feature of .net. First line of code call the method and assign return value to refobj. Second line of code get the Type of the object and than following line of code get the property of anonymous type and print value of it.
Check out full Source code of to test all technique we discuss
using System;p
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            dynamic newtype= p.AnonymousReturn();
            Console.WriteLine("With Dynamic Type");
            Console.WriteLine(newtype.Name + "  " + newtype.EmailID);
            Console.WriteLine();
            Console.WriteLine("With Creation of same anonymous type");
            object o = p.AnonymousReturn();
            var obj = p.Cast(o, new { Name = "", EmailID = "" });
            Console.WriteLine(obj.Name + "  " + obj.EmailID);
            Console.WriteLine();
            Console.WriteLine("With Reflection");
            object refobj = p.AnonymousReturn();
            Type type = refobj.GetType(); 
            PropertyInfo[] fields = type.GetProperties(); 
            foreach (var field in fields) 
            {
                string name = field.Name; 
                var temp = field.GetValue(obj, null);
                Console.WriteLine(name + "  " + temp);
            }

            Console.ReadLine();
        }

         object AnonymousReturn()
        {
            return new { Name = "Pranay", EmailID = "pranayamr@gmail.com" }; 
        }

        T Cast<T>(object obj, T type) { return (T)obj; }

        public static void Write()
        {
            Program p = new Program();
            object obj = p.AnonymousReturn();
            
        }
    }
}
Output 


Conclusion
So Now with the help of the above techniques its possible to return anonymous types form the method.
Hope you guys like it. please rate it and leave your comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
GeneralMy vote of 4 Pin
Naman Kumar Sinha1-Nov-12 21:41
Naman Kumar Sinha1-Nov-12 21:41 
SuggestionIf you are too lazy to create a class, use at least "Tuple"... PinPopular
Andreas Gieriet27-Oct-12 3:14
professionalAndreas Gieriet27-Oct-12 3:14 
GeneralRe: If you are too lazy to create a class, use at least "Tuple"... Pin
shumakercs16-May-13 8:49
shumakercs16-May-13 8:49 
GeneralRe: If you are too lazy to create a class, use at least "Tuple"... Pin
Andreas Gieriet16-May-13 10:17
professionalAndreas Gieriet16-May-13 10:17 
GeneralMy vote of 3 PinPopular
  Forogar  26-Oct-12 5:43
professional  Forogar  26-Oct-12 5:43 
GeneralRe: My vote of 3 Pin
Pranay Rana26-Oct-12 8:21
professionalPranay Rana26-Oct-12 8:21 
GeneralRe: My vote of 3 Pin
Paulo Zemek26-Oct-12 11:54
mvaPaulo Zemek26-Oct-12 11:54 
GeneralMy vote of 3 PinPopular
Paulo Zemek26-Oct-12 3:29
mvaPaulo Zemek26-Oct-12 3:29 
GeneralRe: My vote of 3 Pin
Florian Rappl18-Sep-13 0:42
professionalFlorian Rappl18-Sep-13 0:42 
QuestionMy 3: all three are awkward... PinPopular
Andreas Gieriet25-Oct-12 23:49
professionalAndreas Gieriet25-Oct-12 23:49 
GeneralMy 5 Pin
Shahriar Iqbal Chowdhury/Galib23-Oct-12 1:00
professionalShahriar Iqbal Chowdhury/Galib23-Oct-12 1:00 
GeneralMy vote of 4 Pin
Ismail Mayat17-Oct-12 21:27
Ismail Mayat17-Oct-12 21:27 
GeneralMy vote of 4 Pin
Anurag Sarkar16-Oct-12 8:43
Anurag Sarkar16-Oct-12 8:43 
GeneralMy vote of 2 Pin
Florin Bombeanu16-Oct-12 2:30
Florin Bombeanu16-Oct-12 2:30 
GeneralRe: My vote of 2 Pin
Pranay Rana16-Oct-12 2:47
professionalPranay Rana16-Oct-12 2:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.