Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Return Anonymous type

0.00/5 (No votes)
25 Oct 2012 1  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here