A question came up on the newsgroups of how to get the Guid assigned to a Type via a GuidAttribute. Typically this will be defined when creating a manged Class/Interface to match a COM exposed CoClass/Interface. The desktop exposes a GUID property of the Type class. The workaround for the Compact Framework is fairly straight-forward and for convenience I have posted an amendment to my solution below in the form of an Extension method. This means that from your code you can achieve the desired result with Type.GetGUID() – which is as near as can be to the desktop syntax:-
- /// <summary>
- /// Extension method to get the GUID associated with the Type.
- /// </summary>
- /// <param name=”t”>the Type.</param>
- /// <returns>The GUID associated with the Type.</returns>
- public static Guid GetGUID(this Type t)
- {
- Guid typeGuid = Guid.Empty;
- object[] attributes = t.GetCustomAttributes(false);
- foreach (object o in attributes)
- {
- if (o is GuidAttribute)
- {
- //has GuidAttribute – get the value
- GuidAttribute ga = (GuidAttribute)o;
- typeGuid = new Guid(ga.Value);
- }
- }
- return typeGuid;
- }
I have switched to using Live Writer for blog posts (no idea why I didn’t try it before) and it has much better support for code formatting especially with the “Paste as VS Code” plug-in.