Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type.GetMember & MemberInfo.GetCustomAttributes missing (C# PCL .NET 4.6)

I am probably being really stupid here.

I have updated on of my solutions to start using .NET 4.6. One of my PCL projects does some reflection on an enum. I have updated the PCL compatibility, and fixed the empty project.json file it created. However, this PCL project no longer builds as it doesn't recognise either Type.GetMember() or MemberInfo[x].GetCustomAttribute(...)

The code that I have been using, and was working until today is:

        MemberInfo[] info = e.GetType().GetMember(e.ToString());
        if (info != null && info.Length > 0)
        {
            object[] attributes = info[0].GetCustomAttributes(typeof(Description), false);
            if (attributes != null && attributes.Length > 0)
                return ((Description)attributes[0]).Text;
        }

        return e.ToString();

The project only references the .NET library which is in the following path:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETPortable\v4.5\Profile\Profile7\

The project has automatically supported Xamarin platforms too as part of the configuration of the PCL.

Any thoughts would be massively appreciated.

like image 290
David Hamilton Avatar asked Jan 18 '26 20:01

David Hamilton


1 Answers

OK, so this took a while (and forgot it was even a problem!!)

However the above comments pointed me in the right direction, with one big problem that it was trying to give me Attributes to the Class (main enum) rather than the enum elements themselves. The link in the comment above took me to using GetTypeInfo in the first line of code, this had to be replaced to GetRuntimeField

A small tweak meant I ended up with something along the following lines:

public static string ToDescription(this ArtistConnection e)
{
    var info = e.GetType().GetRuntimeField(e.ToString());
    if (info != null)
    {
        var attributes = info.GetCustomAttributes(typeof(Description), false);
        if (attributes != null)
        {
            foreach (Attribute item in attributes)
            {
                if (item is Description)
                    return (item as Description).Text;
            }
        }
    }

    return e.ToString();
}
like image 174
David Hamilton Avatar answered Jan 21 '26 09:01

David Hamilton