DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How to Return Anonymous Type

Pranay Rana user avatar by
Pranay Rana
·
Oct. 11, 12 · Interview
Like (0)
Save
Tweet
Share
7.88K Views

Join the DZone community and get the full member experience.

Join For Free
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>

 

Anonymous type

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Configure AWS Glue Job Using Python-Based AWS CDK
  • How to Cut the Release Inspection Time From 4 Days to 4 Hours
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • The Enterprise, the Database, the Problem, and the Solution

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: