Get SPGroup, If Not Available, Create!

When developing for calls to SPGroup objects in SharePoint, often times it is best to guarantee that the group exists by placing a creation guard clause in that will create the SPGroup if it is not available off the SPWeb from the initial query.

The GetGroupOrCreate method provided below does just that:

public static SPGroup GetGroupOrCreate(SPWeb web, string name, string description, SPUser owner, SPUser defaultUser, bool associate)
SPGroup groupToReturn = null;
foreach (SPGroup group in web.SiteGroups)
if (!group.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) continue;

groupToReturn = group;

if (groupToReturn == null)
web.SiteGroups.Add(name, owner, defaultUser, description);
groupToReturn = web.SiteGroups[name];
if (associate && !web.AssociatedGroups.Contains(groupToReturn))
return groupToReturn;
} [/csharp]

The SPWeb parameter is the web associated with the SPGroup you wish to query or create

The name parameter represents the name of the group to query or create

The description parameter provides a description for the SPGroup if creation is required

The owner parameter is the owner of the SPGroup represented by an SPUser object

The defaultUser parameter is the first SPUser to be put into the SPGroup

The boolean associated defines whether the SPGroup should be added to the SPWeb.AssociatedGroups collection

It is important to note that I am using InvariantCultureIgnoreCase to perform a case-insensitive string comparison using the word comparison rules of the invariant culture.