Categories
Compact Framework

Replacement for Type.GUID

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:-

  1. /// <summary>
  2. /// Extension method to get the GUID associated with the Type.
  3. /// </summary>
  4. /// <param name=”t”>the Type.</param>
  5. /// <returns>The GUID associated with the Type.</returns>
  6. public static Guid GetGUID(this Type t)
  7. {
  8.     Guid typeGuid = Guid.Empty;
  9.     object[] attributes = t.GetCustomAttributes(false);
  10.     foreach (object o in attributes)
  11.     {
  12.         if (o is GuidAttribute)
  13.         {
  14.             //has GuidAttribute – get the value
  15.             GuidAttribute ga = (GuidAttribute)o;
  16.             typeGuid = new Guid(ga.Value);
  17.         }
  18.     }
  19.  
  20.     return typeGuid;
  21. }

 

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.

By Peter Foot

Microsoft Windows Development MVP