As part of .NET 7, developers now have the ability to tag strings using the StringSyntax attribute. These tags inform tools such as Visual Studio as to the nature of the string. For example, you can mark the string as containing JSON or RegEx, and Visual Studio will apply the appropriate syntax highlighting.
Also shown in the image above is a code-completion-like feature that displays the definition of formatting characters for date/time format strings.
The StringSyntax
attribute can be applied to fields, properties, and parameters. The list of built-in syntax types is shown below, but developers can supply their own as well:
- CompositeFormat: The syntax identifier for strings containing composite formats for string formatting.
- DateOnlyFormat: The syntax identifier for strings containing date format specifiers.
- DateTimeFormat: The syntax identifier for strings containing date and time format specifiers.
- EnumFormat: The syntax identifier for strings containing Enum format specifiers.
- GuidFormat: The syntax identifier for strings containing Guid format specifiers.
- Json: The syntax identifier for strings containing JavaScript Object Notation (JSON).
- NumericFormat: The syntax identifier for strings containing numeric format specifiers.
- Regex: The syntax identifier for strings containing regular expressions.
- TimeOnlyFormat: The syntax identifier for strings containing time format specifiers.
- TimeSpanFormat: The syntax identifier for strings containing TimeSpan format specifiers.
- Uri: The syntax identifier for strings containing URIs.
- Xml: The syntax identifier for strings containing XML.
At the time of writing, Visual Studio only supports some of these syntax types. Presumably the rest will be incorporated into future versions.
Since StringSyntax
is a normal attribute, Roslyn code analyzers could be written to warn about syntax errors in strings at compile time. One could also create an analyzer that detects mistakes such as assigning an XML-tagged string to a property that is expecting a JSON-tagged string.