Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I wanted to update a web application web.config via Powershell, and found this post really helpful.

I'm intrigued as to how to this bit of code works, particularly the $closedMethod / MakeGenericMethod stuff.

$method = [Microsoft.Sharepoint.Administration.SPServiceCollection].GetMethod("GetValue", [Type]::EmptyTypes)
$closedMethod = $method.MakeGenericMethod([Microsoft.SharePoint.Administration.SPWebService])
$webService = $closedMethod.Invoke($webApp.Farm.Services, [Type]::EmptyTypes) 

Any tips?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

This uses the .NET feature of Reflection to get information about a method within a class (in this case, the GetValue method within the SPServiceCollection class, then the method is "Invoked".

The bit that might be slightly confusing is the MakeGenericMethod call, which returns a MethodInfo object which represents the method declaration of type SPWebService (with type-assigned parameters), instead of a generic declaration.

The reason this is used (I can only assume from the blog post you linked to) is that you're calling a generic method in the web service, and thus you need to pass an object of unknown type (unknown at runtime, but known at compile-time) - using GetGenericMethod lets you call the generic method with a specific type at compile time.

This page demonstrates quite clearly the difference between a generic method invoked normally, and one invoked where the type parameters are set at compile time:

http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.makegenericmethod(v=VS.90).aspx

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.