3

Context

I have a List<SPPrincipal> that is a mix of SPGroup, SPUser and AD Users.

Problem

I'm trying to find out how to determine if an SPPrincipal I have is an SPUser, SPGroup or an AD user.

Attempted solutions

Ive tried something like:

foreach (var principal in listOfPrincipals
{
  if (principal is SPGroup) { /* do stuff */ }
}

But this does not appear to work.

Does anyone have any ideas about how to resolve this information ?

Update

After fiddling a bit I came to this solution that seems to work for SPGroup and SPUser

foreach (SPPrincipal subscriber in listOfSubscriberUsersAndGroups)
{
   var isGroup = subscriber is SPGroup;
   var isUser = subscriber is SPUser;
}

Here an SPGroup is found correctly, and SPUser is found correctly.

Update 2

The above actually works like it is supposed to. My mistake was that the SPPrincipal I was testing was actually a Domain-group, and not an SPGroup (red ears)

2 Answers 2

3

Are you sure that you provided correct code snippet? if it is true, the VS should throw this exception: 'Microsoft.SharePoint.SPPrincipal' is a 'type' but is used like a 'variable' and break build action. You should use principal variable instead of SPPrincipal class:

foreach (var principal in listOfPrincipals)
{
  if (principal is SPGroup) { //do stuff }
}

I tested this code:

SPPrincipal pr = SPContext.Current.Web.Groups[0];

if (pr is SPGroup)
{
    Console.WriteLine("Group");
}

And it works correctly.

5
  • I would prefer using the 'as' operator instead of 'is' operator. Because if the SPPrincipal is not a group, then 'is' will throw an exeption while 'as' will return null. So something like: if((pr as SPGroup) != null){ //do stuff } Commented Aug 15, 2012 at 12:51
  • @VardhamanDeshpande, if SPPrincipal is not a group the code in true branch does not invoking. Also this line pr is SPGroup does not throw the error. I don't undestand when we can have this error?
    – Alexander
    Commented Aug 15, 2012 at 15:50
  • My Bad. I was wrong about the exception part. But still I would prefer "as" over "is" because "is" checks the type of object twice while "as" checks it only once. See here: stackoverflow.com/questions/496096/… Commented Aug 15, 2012 at 16:21
  • I like this phrase - it depends :) if you would like to choose some item by class type the best way is to use "is". But I'm agree with you if you should cast this class and use it :)
    – Alexander
    Commented Aug 15, 2012 at 16:28
  • @Alexander:sorry, I made a mistake in my write-up, as I was writing from memory.. I am using the variable.. I will correct the write-up
    – user3801
    Commented Aug 15, 2012 at 17:24
1

You need to use the propriety Member

foreach (var principal in listOfPrincipals
{
  if (principal.Member is SPGroup) { /* do stuff */ }
  else if (principal.Member is SPUser) { /* do stuff */ }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.