How do I replace the ReturnType of a IMethod?

I looked into using the ModificationUtil static, but it expects an ITreeNode. So I guess the question is either: 1) How do I get the tree node representation of the ReturnType of a method or 2) Is there another way to outright replace the return type?


You need to get a hold of IMethodDeclaration, rather than IMethod, and then you can use IMethodDeclaration.SetType().

The IMethod interface is the semantic information about the method, and IMethodDeclaration is the declaration in the source code. If you're processing a source file in a daemon stage, you'll already have access to the IMethodDeclaration as you're walking the syntax tree. If you've only got an IMethod, you can get it from method.GetDeclarations, which should return you a single item (although you might get more with partial methods). Once you've got the IMethodDeclaration, you can use IMethodDeclaration.SetType() (well, technically, it's ITypeOwnerDeclaration.SetType...).

You need to pass in an instance of IType to change the return type. You can get this from one of the static methods on TypeFactory, e.g. TypeFactory.CreateTypeByCLRName("System.String", methodDeclaration.GetPsiMOdule(), methodDeclaration.GetResolveContext()).


That worked, thanks! I did have a reference to an IMethodDeclaration, but the SetType method was not obvious as to its purpose.


Please sign in to leave a comment.