Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get properties of a Dynamic Type

I would like to know how to get the properties of my dynamic type.

This is the function to get the List,

var result = _files.GetFileContent(reportId).Result;

As example I get an object returned like this :

enter image description here

When I open it, you can see the properties I have :

enter image description here

The Idea is that I never know the properties. They can change over time. So I want a list which is filled with all the properties. So I can dynamically use them.

How Can I get the properties from the first item (ChargesDelta_DIFF_5, ChargesEfile_RIGHT,ChargesGecep_LEFT, etc)?

like image 523
Walter Avatar asked Jan 12 '17 12:01

Walter


People also ask

How to Get properties from dynamic object C#?

In C#, you can access dynamic properties by obtaining a PropertyObject reference from the specific object reference using the AsPropertyObject method on the object.

What are the dynamic properties?

Dynamic properties of structures characterize a system in form of natural frequencies, damping and mode shape. These dynamic properties are used to formulate mathematical model for its behavior. The evaluation of dynamic properties of is Nnown as modal analysis.

What is dynamic properties in C#?

Dynamic objects expose members such as properties and methods at run time, instead of at compile time. This enables you to create objects to work with structures that do not match a static type or format.

Is it good practice to use dynamic in C#?

The short answer is YES, it is a bad practice to use dynamic. Why? dynamic keyword refers to type late binding, which means the system will check type only during execution instead of during compilation.


2 Answers

You can use reflection to get the properties out and convert it to a dictionary:

dynamic v = new { A = "a" };

Dictionary<string, object> values = ((object)v)
                                     .GetType()
                                     .GetProperties()
                                     .ToDictionary(p => p.Name, p => p.GetValue(v));
like image 170
Patrick Hofman Avatar answered Oct 16 '22 05:10

Patrick Hofman


If someone is still struggling with this (as I did), this might be useful.

Let's say data is the dynamic you want to list all properties from:

This worked for me

using System.ComponentModel;

...

dynamic data = new {
    value1 = 12,
    value2 = "asdasd",
    value3 = 98,
    value4 = "pgiwfj",
};

foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(data))
{
    Console.WriteLine("PROP: " + prop.Name);
}

...

Then it would output:

  • PROP: value1
  • PROP: value2
  • PROP: value3
  • PROP: value4

Source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/251e4f3d-ce90-444a-af20-36bc11864eca/how-to-get-list-of-properties-of-dynamic-object-?forum=csharpgeneral

like image 35
Rodrigo.A92 Avatar answered Oct 16 '22 06:10

Rodrigo.A92