37

I'm putting together an app that interfaces with Stack API and have been following this tutorial (although old API version it still works). My problem is that when using this within the Windows 8 Store App I'm contrained by the .NETCore Framework which doesn't support the GetCustomAttributes method found below:

    private static IEnumerable<T> ParseJson<T>(string json) where T : class, new()
    {
        var type = typeof (T);
        var attribute = type.GetCustomAttributes(typeof (WrapperObjectAttribute), false).SingleOrDefault() as WrapperObjectAttribute;
        if (attribute == null)
        {
            throw new InvalidOperationException(
                String.Format("{0} type must be decorated with a WrapperObjectAttribute.", type.Name));
        }

        var jobject = JObject.Parse(json);
        var collection = JsonConvert.DeserializeObject<List<T>>(jobject[attribute.WrapperObject].ToString());
        return collection;
    }

My question is two-fold. What exactly does the GetCustomAttributes do and is there an equivalent to this method within the constrains of Windows 8 Store App realm?

Lee
  • 567
  • 5
  • 18
James Mertz
  • 8,459
  • 11
  • 60
  • 87

2 Answers2

67

You need to use type.GetTypeInfo(), which then has various GetCustomAttribute methods (via extension methods), or there is .CustomAttributes which gives you the raw information (rather than materialized Attribute instances).

For example:

var attribute = type.GetTypeInfo().GetCustomAttribute<WrapperObjectAttribute>();
if(attribute == null)
{
    ...
}
...

GetTypeInfo() is the pain of .NETCore for library authors ;p

If .GetTypeInfo() doesn't appear, then add a using System.Reflection; directive.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    I spent about two hours trying to find this. Should have asked sooner :P – James Mertz Oct 10 '12 at 08:28
  • 1
    @KronoS heh; I had the pleasure of converting an existing library that made extensive use of reflection... me and .NETCore are now intimately knowledgeable of each-other, and not in a good way. This is just the tip of the iceberg if you do lots of reflection ;p – Marc Gravell Oct 10 '12 at 09:07
  • 2
    One thing to add on .NetCore (with xproj), the TypeInfo extensions are in "System.Reflection.Extensions" package: "dotnet5.4": { "dependencies": { "System.Reflection.Extensions": "4.0.1-beta-23516" } } – Spi Nov 25 '15 at 13:34
1

Add the System.Reflection.TypeExtensions nugget package to your project; it has GetCustomAttributes extension.

(for VS 2017) something like this.

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.6'">
    <PackageReference Include="System.Reflection.TypeExtensions">
        <Version>4.3.0</Version>
    </PackageReference>
</ItemGroup>