.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

How to Return Anonymous Type

10.10.2012
| 2912 views |
  • submit to reddit
First, some quick facts about anonymous types:
  • Anonymous types are reference types derived form system.objects.
  • Properties of the anonymous type are read-only.
  • If two anonymous types have the same properties and same order, then the compiler treats it as the same type.
  • Anonymous types have method scope. If you want to return anonymous type form the method then you have to convert it in object type. But this is not good practice.
You can read more about anonymous types here. Now, if you want to return anonymous type you need to cast it in object.
I'm going to show three different ways 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 the following method that 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 intelligence support, as we are using dynamic type. And you need to remember the property name and type also.

Way 2: Handle by creating the 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, the following method casts the object.

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

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 makes use of the reflection feature of .net. The first line of code calls the method and assigns return value to refobj. Second line of code gets the type of the object and then the following line of code gets the property of anonymous type and prints its value.

Check out the full source code to test all of the techniques above:

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();
             
        }
 
    }
}
 
</t>

 

Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)