I have an extension method that I've used for years in WinForms, but not since I've tried to use it in a new WPF project. The method:
public static String GetDescription(this Enum value)
{
//var info = value.GetType().GetField(value.ToString());
//if (info != null)
//{
// var attributes = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
// if (attributes != null && attributes.Length > 0)
// return attributes[0].Description;
//}
//return value.ToString();
var info = value.GetType().GetField(value.ToString());
var attributes = Attribute.GetCustomAttributes(info);
if (attributes.Length > 0 && (attributes[0] is System.ComponentModel.DescriptionAttribute))
return ((System.ComponentModel.DescriptionAttribute)attributes[0]).Description;
return value.ToString();
}
The first chunk (that is commented out) is the original method. The second chunk is a slightly different version of it that I've been testing with. If I force the return line with the cast to execute, I get this exception:
The full text of the exception from that dialog is:
Additional information: [A]System.ComponentModel.DescriptionAttribute cannot be cast to [B]System.ComponentModel.DescriptionAttribute. Type A originates from 'System.ComponentModel.Primitives, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' in the context 'Default' at location 'C:\TFS_Local\Antero\AnteroWPF\bin\Debug\System.ComponentModel.Primitives.dll'. Type B originates from 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll'.
The two assemblies involved seem to be:
System.ComponentModel.Primitives.dll (exists in the build bin directory...not entirely sure how it got there)
System.dll (referenced directly from GAC, for obvious reasons)
I'm completely lost here. If I remove the ComponentModel DLL, that becomes the exception. Even though the exception claims that System has the type, no use of it seems possible. I.e. System.ComponentModel.DescriptionAttribute does not seem to be a valid thing to do in the absence of the corresponding DLL.
So, if I remove one and that fails, and the other is complete unusable...then why is this exception even occurring?!
EDIT:
I think it's worth nothing that if I inspect the value of attributes in memory, I see that the array does have a single item and it is of type System.ComponentModel.DescriptionAttribute.
