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

Return Anonymous type

By , 25 Oct 2012
 
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
Member

Microsoft C# MVP

 
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:



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberNaman Kumar Sinha1 Nov '12 - 21:41 
Excellent Write-up. can you please add pros and cons of each approach?
SuggestionIf you are too lazy to create a class, use at least "Tuple"... [modified]memberAndreas Gieriet27 Oct '12 - 3:14 
As others already commented, your article may be an *academic* exercise, for sure not as a practical advise.
Why would one turn off strong typed programming without cause?
If one is too lazy to create its own type, use at least Tuple<T1, T2>[^].
E.g. your example function would look as follows:
Tuple<string, string> TupleReturn()
{
    return new Tuple<string, string>("Pranay", "pranayamr@gmail.com");
}
 
Using:
var obj = TupleReturn();
Console.WriteLine("1st = {0}", obj.Item1);
Console.WriteLine("2nd = {0}", obj.Item2);
 
The draw back is, that the tuple is not self documented.
 
I still vote for writing your own class, even for this simple case, e.g.
internal class UsersEmail
{
    public UsersEmail(string name, string email)
    {
        Name = name;
        EMail = email;
    }
    public string Name { get; private set; }
    public string EMail { get; private set; }
}
UsersEmail SpecificReturn()
{
    return new UsersEmail("Pranay", "pranayamr@gmail.com");
}
 
Usage:
var obj = SpecificReturn();
Console.WriteLine("Name  = {0}", obj.Name);
Console.WriteLine("EMail = {0}", obj.EMail);
 
Cheers
Andi

modified 27 Oct '12 - 11:54.

GeneralRe: If you are too lazy to create a class, use at least "Tuple"...membershumakercs16 May '13 - 8:49 
Andi, it is good advice to encourage the use of strong typing, and avoid falling into a habit of using dynamic or anonymous types to avoid creating classes. However, there are legitimate uses of these. If you look at many successful frameworks/language features such as LINQ, you will see anonymous or dynamic types being used throughout, and these frameworks actually bring compile time safety into an area where previously things like ADO.NET were not strongly typed and involved passing strings around quite a bit. So it is a bit of irony.
 
My point, there are appropriate usages of these language constructs. I think it is harsh to accuse the author of advocating laziness. No where does this article encourage the use of these types. No where does it say anything like "you should really use anonymous types instead of classes". Rather it simply provides some recipes for dealing with them in certain scenarios. It should indeed be very rare that you are passing or returning an anonymous type as a return/parameter, but on those rare occasions, this article provides several examples of how to deal with those cases.
 
For example, in MVC you have a JsonResult.Data property which it is pretty common to assign an anonymous type projection to. In rare cases you may need to restructure that anonymous type in order to facilitate a different JSON structure, which requires casting the object into a dynamic type in order to access its properties.
GeneralRe: If you are too lazy to create a class, use at least "Tuple"...memberAndreas Gieriet16 May '13 - 10:17 
I'm harsh in my criticism, you are right. It's not meant personnal. I review many thousands of lines of code every year and my finding is that such usages are most of the time "laziness" of some kind. A proper use of types is not "concidence" but deliberate design and implementation decision.
Why should one want to use an anonymous type accross function boundaries. The language does not support it in a type safe manner, so why "abuse" dynamic for that while moveing the type check to run-time without cause.
Simply since you can do things, does not mean you should.
BTW: you refer to LINQ. That does not use dynamic. Or can you show me any of these instances (LINQ bases on IEnumerable<...> and IQueryable<...>, or did I miss something).
dynamic is to mimic or interop with dynamic languages or to ease introp with "legacy" COM wrapper interfaces. E.g. Did you ever implement VSTO based functionality? It's better than without dynamic, but still a pain since with dynamic you have no edit time nor compile time support of any kind.
 
My advise: Use it with care. Document it well. Tell why you used that approach instead of the type safe approach.
 
Cheers
Andi
GeneralMy vote of 3memberForogar26 Oct '12 - 5:43 
This is very interesting as an academic exercise but seems to be bad practice generally; especially from a maintenance point of view.
 
However, my main complaint is that you don't provide any reason to do this. A real-world example of why you would need to do this would go a long way to providing incentive to take any notice of your article.
GeneralRe: My vote of 3memberPranay Rana26 Oct '12 - 8:21 
there are some cases during development where I found we need to return anonymous type , for that we cannot create new class instead of the this kind of technique useful...

GeneralRe: My vote of 3mvpPaulo Zemek26 Oct '12 - 11:54 
I will really love to see those cases explained.
I simple can't see any of those cases.
As I said in my vote of 3 (I am commenting on another vote) I only consider valid to return an anonymous object if the receiver is using reflection to display all the properties (or in fact using some kind of reflection to do something). For all other cases, I will consider real types much better.
After all, even if you don't create a new type, the compiler does... so it is not something that will reduce the executable size.
GeneralMy vote of 3mvpPaulo Zemek26 Oct '12 - 3:29 
I am only voting three because I considered it interesting to see the use of the dynamic keyword and even the creation of that awkward Cast method, showing that the object is really of the same type.
 
But aside from interesting, those are all really bad practices.
Returning an anonymous type? Well, if the receiver is going to use reflection to display it, OK... for all the other cases, don't do it!
 
Using dynamic to access that type?
Well, even if you don't create a full class, the compiler is creating a full class for you, but instead of using that class directly, you are going to a dynamic approach, which will not support refactoring and will not generate compile time errors if you write the wrong property name.
 
And the cast one... hey, if you KNOW that it is the same type as to write a "new" with the same property names and fill it with the same value types (even if you used an empty string, it is still a string), then why not lose time creating a type?
Also, this solution will not support either refactoring and, worst, if you simple add a new property on the method that returns the anonymous object, all the places that used that cast will fail!
 
Edit: I corrected good practices by bad practices... I may be thinking they are not good practices and I wrote only good...
QuestionMy 3: all three are awkward...memberAndreas Gieriet25 Oct '12 - 23:49 
The obvious solution would be: don't do return anonymous types from methods.
Make a simple class.
The maintainer of your code will thank you!
Just since you *could* do it does not mean you *should* do it...
Cheers
Andi
PS: you could add the explicit class case in your examples and you see immediately its benefits in maintainability and redability - no awkward casting, no reflection (explicit or implicit by use of dynamic type).
GeneralMy 5memberShahriar Iqbal Chowdhury23 Oct '12 - 1:00 
Good examples
GeneralMy vote of 4memberIsmail Mayat17 Oct '12 - 21:27 
Nice very useful post will make use of this.
GeneralMy vote of 4memberonurag1916 Oct '12 - 8:43 
Nice.
GeneralMy vote of 2memberFlorin Bombeanu16 Oct '12 - 2:30 
Intelligence support?
GeneralRe: My vote of 2memberPranay Rana16 Oct '12 - 2:47 
updated spell mistake ..hope you update your vote

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

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