Return Anonymous Type in C#

Quick facts about Anonymous types

  • Anonymous types are reference types derived form system.objects.

  • Properties of the Anonymous type is read only.

  • If two Anonymous types have the same properties and the same order then the compiler treats its as the same type. But if both are in one assembly.

  • Anonymous types have method scope. If you want to return an Anonymous type from a method you must convert it to an object type. But that is not a good practice.

You can read more on the following blog about this: Anonymous types.

As in the preceding facts you cannot return an anonymous type from a method, if you do want to return one then you need to cast it to an object.

Now in the following article I will do the same, return an anonymous type as an object and show three ways to handle it.

  • Solution 1: Handle using Dynamic type.

  • Solution 2: Handle by creating the same anonymous type.

  • Solution 3: Handle using Reflection.

To understand each solution I created the following method that returns an anonymous type:

  1. object AnonymousReturn()  
  2. {  
  3.    return new { Name = "Pranay", EmailID = "[email protected]" };   
  4. }  
Solution 1: Handle using Dynamic type
  1. dynamic newtype= AnonymousReturn();  
  2. Console.WriteLine(newtype.Name + " " + newtype.EmailID);  
As you see in the preceding example the first line of code calls a method returning an anonymous type as an object and assigns the return value to the dynamic type. The second line of code just prints the property value of the anonymous type.

Note: There is no intellisense support since we are using a dynamic type. And we need to remember the property name and type also.

Solution 2: Handle by creating the same anonymous type
  1. object o = AnonymousReturn();  
  2. var obj = Cast(o, new { Name = "", EmailID = "" });  
  3. Console.WriteLine(obj.Name + " " + obj.EmailID);  
This solution returns the value of the anonymous type and is assigned to the object. The next line of code casts the object to the same anonymous type. To accomplish this task the following method does the casting of the object.
  1. T Cast<T>(object obj, T type) { return (T)obj; }  
This done song type conversation and provides intelligence support.

Solution 3: Handle using Reflection
  1. object refobj = AnonymousReturn();  
  2. Type type = refobj.GetType();   
  3. PropertyInfo[] fields = type.GetProperties();   
  4. foreach (var field in fields)   
  5. {  
  6.    string name = field.Name;   
  7.    var temp = field.GetValue(obj, null);  
  8.    Console.WriteLine(name + "  " + temp);  
  9. }  
This solution uses the reflection feature of .Net. The first line of code calls the method and assigns a return value to refobj. The 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 the value of it.

Check out the full source code to test all techniques we discussed:
  1. using System;p  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Reflection;  
  6.   
  7. namespace Test  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             Program p = new Program();  
  14.             dynamic newtype= p.AnonymousReturn();  
  15.             Console.WriteLine("With Dynamic Type");  
  16.             Console.WriteLine(newtype.Name + "  " + newtype.EmailID);  
  17.             Console.WriteLine();  
  18.             Console.WriteLine("With Creation of same anonymous type");  
  19.             object o = p.AnonymousReturn();  
  20.             var obj = p.Cast(o, new { Name = "", EmailID = "" });  
  21.             Console.WriteLine(obj.Name + "  " + obj.EmailID);  
  22.             Console.WriteLine();  
  23.             Console.WriteLine("With Reflection");  
  24.             object refobj = p.AnonymousReturn();  
  25.             Type type = refobj.GetType();   
  26.             PropertyInfo[] fields = type.GetProperties();   
  27.             foreach (var field in fields)   
  28.             {  
  29.                 string name = field.Name;   
  30.                 var temp = field.GetValue(obj, null);  
  31.                 Console.WriteLine(name + "  " + temp);  
  32.             }  
  33.   
  34.             Console.ReadLine();  
  35.         }  
  36.   
  37.          object AnonymousReturn()  
  38.         {  
  39.             return new { Name = "Pranay", EmailID = "[email protected]" };   
  40.         }  
  41.   
  42.         T Cast<T>(object obj, T type) { return (T)obj; }  
  43.   
  44.         public static void Write()  
  45.         {  
  46.             Program p = new Program();  
  47.             object obj = p.AnonymousReturn();  
  48.               
  49.         }  
  50.     }  
  51. }  
Output

Output

Conclusion

So now using the preceding techniques it is possible to return anonymous types from a method.

I hope you guys like it. Please rate it and leave your comments.


Similar Articles