Platinum Partner
dotnet,tutorial,c-sharp,anonymous type

How to Return Anonymous Type

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}