Language Injections in C#
If a string literal contains some other formal language, such as regular expression, HTML, and so on, JetBrains Rider can provide code inspection, quick-fixes, code completion, Context Actions, and many other features specific to this language right inside this excerpt.
JetBrains Rider supports the following languages inside C# string literals:
JavaScript
HTML
CSS
JSON
XML
SQL
JetBrains Rider allows you to manually mark the literal as containing specific language in one of the following ways:
Use the context action, which actually tells JetBrains Rider to mark the symbol range corresponding to the string, save this range in its internal database and keep track of it as the containing file changes. This way is very quick and straightforward, but there are two downsides: the range can be lost after an external file change, such as a VCS merge, and the injection marked this way will only be tracked locally:
Mark method parameters, properties, and fields accepting regular expressions with the
[RegexPatternAttribute]
from JetBrains.Annotations. This is the recommended way for regular expressions.Put a comment
/*language=javascript|html|regexp|jsregexp|json|css|xml*/
before the string literal. Granted, these comments require some typing, and you can even think of them as contaminating your code. However, they make your intention clear to everyone who reads your code, they will not get lost, and anyone opening your code with JetBrains Rider will get the same features in the marked strings.
By the way, the format of comments is compatible with JetBrains ReSharper and IntelliJ Platform-based IDEs. You can also useprefix=
andpostfix=
parameters in the comments. For example, if a string only contains a list of CSS properties, you can add the following comment before it://language=css prefix=body{ postfix=}
. This will make JetBrains Rider resolve the string as valid CSS.