cyberbobcat
cyberbobcat

Reputation: 1179

C# generic method with one parameter of multiple types

I'm having a problem writing a generic method to retrieve AD Groups or Users with a parameter that can be one of two types - either System.DirectoryServices.AccountManagement GroupPrincipal or UserPrincipal

The method is as follows:-

private static IEnumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
{
   PrincipalSearcher ps = new PrincipalSearcher();
   ps.QueryFilter = GroupOrUserPrincipal;

   etc.........
}

The problem is the GroupOrUserPrincipal is showing the following error:-

Cannot implicitly convert type 'T' to System.DirectoryServices.AccountManagement.Principal

Am I able to do this or am I missing something ?

Upvotes: 3

Views: 5857

Answers (4)

Johannes Kommer
Johannes Kommer

Reputation: 6451

You need to specify a type parameter constraint; for example:

private static IEnumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal) where T: Principal

This limits the classes that can be used as T to only classes of type Principal or a subclass of Principal. The C# compiler then knows that everything passed to GetGroupsOrUsers(...) will be of a type compatible with Principal and will no longer error.

Upvotes: 3

Ricibob
Ricibob

Reputation: 7705

Possibly you want to look at Generic Contraints in particular a derivation contraint where your various T objects all impliment a given interterface. Eg

where T : Principle

Upvotes: 3

Jens
Jens

Reputation: 25563

You should restrict T to types that your method makes sense for:

private static IENumerable<string> GetGroupsOrUsers<T>(T GroupOrUserPrincipal)
        where T : Principal
{
      // .....

That prevents calls of GetGroupsOrUsers<int>, and lets T be implicitly converted to Principal, fixing your error (or so I hope).

Upvotes: 6

Fischermaen
Fischermaen

Reputation: 12458

You have to write a cast in this line:

ps.QueryFilter = (Principal) GroupOrUserPrincipal; 

Upvotes: 0

Related Questions