.NET Components for Mobility

Peter Foot

Microsoft Device Application Development MVP

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.

Comments

No Comments

About PeterFoot

Peter Foot is co-author of the Microsoft Mobile Development Handbook published by Microsoft Press. Peter has been awarded the Microsoft Most Valuable Professional (MVP) accolade since 2003 for his involvement in the Microsoft .NET Compact Framework developer community. Alongside an active presence in several online forums and communities, attendance at developer conferences and involvement in shared-source projects, Peter has also written a number of technical articles and maintains an active technical blog.
Copyright © 2001-2010 In The Hand Ltd. All rights reserved. Terms of Use and Privacy Policy.