Click here to Skip to main content
Click here to Skip to main content

Return Anonymous type

, 25 Oct 2012
Rate this:
Please Sign up or sign in to vote.
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)

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in 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:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionMy 3: all three are awkward... PinmemberAndreas Gieriet25-Oct-12 23:49 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 26 Oct 2012
Article Copyright 2012 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid