Search This Blog

Wednesday, December 21, 2011

C# how to get underlying types from an anonymous type

If you encounter an anonymous type you can get the underlying types using reflection. In my case the source object was of type ‘EntCls81BD186ACCBAB596592C26438762156AD811E’ i.e. unknown to the compiler = dynamically created.


foreach (var possibleRowMatch in sourceDataGrid.ItemsSource)
    var rowProperties = possibleRowMatch.GetType().GetProperties();
    for (int i = 0; i < rowProperties.Length; i++)
        string propertyName = rowProperties[i].Name;
        Type columnType = rowProperties[i].PropertyType;
        var columnValue = possibleRowMatch.GetType().GetProperty(propertyName).GetValue(possibleRowMatch, null);

        //cast to a columnType
        if (columnValue.GetType() == columnType)
            //do something


  1. To create object of Type (create object of a specific type held in a variable of type Type) use Activator class:

    var chartTypeInstance = Activator.CreateInstance(chartType.Type);

  2. To cast to a System.Type use:

    System.Convert.ChangeType(ValueYouWantToConvert, conversionType, null);

    conversionType is of type System.Type.


If you like this post, please leave a comment :)