Always Test Whether Your GUID’s Are Valid!
It is a best practice to not blindly use GUID’s, you should always test whether they are valid or not. This proves helpful in several SharePoint helper methods when you are doing custom SharePoint development, and is something that should be implemented in your corporate standard shared libraries.
Considering that testing for the GUID is a relatively simple process, it is worth taking the time to make sure that you implement a try/catch around it, and pass in the GUID as a string parameter. In order to set up the test of whether a GUID is valid or not, you are going to set up static flagging method (a Boolean) that will take a GUID string as a parameter.
- public static bool isMyGuidValid(string guid)
Then, you must setup a try/catch block that in the try block will intialize a new instnace of the System.Guid class and pass in the string GUID. If it returns true, great!, the GUID is valid!
- new Guid(guid);
- return true;
When the catch block is executed, that means the GUID is not valid, so simply return false.
- return false;
Yeah, it is a pretty simple convention, but you would be surprised how often untested GUID’s are used within WebParts and other SharePoint development pieces. It is a better code practice to test though, especially when the condition that you are building is so easy to construct!