Code Completion: CSharp String

16 views
Skip to first unread message

Peter Join

unread,
Mar 21, 2015, 12:47:50 PM3/21/15
to resharpe...@googlegroups.com
Hi

Could you please share a sample code for Code Completion in CSharp string ?

Thanks

Matt Ellis

unread,
Mar 25, 2015, 7:21:47 AM3/25/15
to resharpe...@googlegroups.com
Hi Peter. If you want to add code completion, you need to create a class that derives from ItemsProviderOfSpecificContext<CSharpCodeCompletionContext>. This will allow you to add items to the completion list at any location in the code.

However, it you're wanting to provide code completion for values of a string literal, you might want to implement a "reference provider" instead. This is much more powerful than providing items in a code completion list, because it allows the contents of the string literal to refer to elements defined elsewhere in the code, for example, the name of a property on the class you're working with. When you create a reference provider, you attach a reference to the string literal node in the abstract syntax tree. ReSharper will try to resolve the reference. If it can't resolve, it's highlighted in red, as an error, even in a string literal. If it is resolved, you can now use it to navigate to the declaration of the symbol, and it will even appear in the results of find usages, and be renamed when the rename refactor is applied. Furthermore, your reference can provide a set of candidate targets for resolving, so you can also have code completion (the candidates are essentially anything that would result in a successful resolve result, e.g. all properties in a class that could be used.)

A simple example of this would be the name argument to an ArgumentNullException. ReSharper creates a reference from this string literal that should resolve to one of the parameters of the method. It can use all of the parameters as candidates, and they'll appear in code completion. When you rename a parameter, the usage in the ArgumentNullException is also renamed. And find usages of the parameter will also include the ArgumentNullException.

You can find out more about reference providers in the devguide (note that this is the first page of a whole section on references). And there's a full example in the source for the xunit.net testing plugin. It has a reference provider for string literals in the [PropertyData("MyPropertyName")] attribute usage.

Regards
Matt
Reply all
Reply to author
Forward
0 new messages