0

I have a simple POCO class with one one public property defined as dynamic. Is it possible to determine the type of this property at runtime? I've tried getting the type using reflection like this:

myObject.GetType().GetProperties();

or this:

System.ComponentModel.TypeDescriptor.GetProperties(myObject);

But both return System.Object rather than the current type. In the Visual Studio debugger I see the type listed as "dynamic {System.DateTime}" or "dynamic {System.Int32}" which suggests it's possible to read the type at runtime. So how does one do it?

Edit - Adding a sample program that shows the issue:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicTypeSample
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTag datatag1 = new DataTag() { Id = Guid.NewGuid(), Name = "datatag1", Value = new DateTime(2014, 9, 12) };
            DataTag datatag2 = new DataTag() { Id = Guid.NewGuid(), Name = "datatag2", Value = (int)1234 };

            var propertyTypes1 = GetPropertyTypes(datatag1);
            var propertyTypes2 = GetPropertyTypes(datatag2);

            foreach (var p in propertyTypes1)
            {
                Console.WriteLine(p.Key + " " + p.Value.ToString());
            }

            foreach (var p in propertyTypes2)
            {
                Console.WriteLine(p.Key + " " + p.Value.ToString());
            }

            Console.ReadLine();
        }

        private static Dictionary<string, Type> GetPropertyTypes(DataTag datatag)
        {
            Dictionary<string, Type> results = new Dictionary<string, Type>();
            foreach (var pi in (typeof(DataTag)).GetProperties())
            {
                results.Add(pi.Name, pi.PropertyType);
            }
            return results;
        }

    }


    public class DataTag
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public dynamic Value { get; set; }
    }
}

The output looks like:
Id Sytem.Guid
Name System.String
Value System.Object
Id Sytem.Guid
Name System.String
Value System.Object

What I'm trying to achieve is:
Id Sytem.Guid
Name System.String
Value System.DateTime
Id Sytem.Guid
Name System.String
Value System.Int32

Greg Enslow
  • 1,438
  • 5
  • 18
  • 28

1 Answers1

0

If I’m not mistaken. What you are doing over there is getting the object properties.

What you could do is use reflection to iterate through the properties to get their basic info and data type.

Maybe you should try something like this :

PropertyInfo[] propsobj = typeof(MyClassType).GetProperties();
foreach(PropertyInfo p in propsobj)
{
    object[] attribs = p.MyProperty;
}

Hope it helps. Cheers!