Did you know you can inject languages into string literals with a comment in #JetBrainsRider? It will enable basic syntax highlighting and *some* code completion in the string literal. Additionally it will give you warnings if the string literal is not valid in the chosen language.

In .NET 7 you will also be able to use the StringSyntaxAttribute https://learn.microsoft.com/dotnet/api/system.diagnostics.codeanalysis.stringsyntaxattribute which also works in #VisualStudio. But attributes can't be used everywhere (e.g. for local variables).

#dotnet @dotnet

StringSyntaxAttribute Class (System.Diagnostics.CodeAnalysis)

Specifies the syntax used in a string.

@bitbonk @dotnet makes me a little sad how close this is to an embedded language-typed-string-literal though.

Like, we’re almost at

JSONObject j = $JSON“””
{ “foo”:”bar” }
“””

With a pluggable compile time validation and parse…

@james_a_hart @bitbonk @dotnet so Rider can have attributes on method parameters to signal to the editor the intended language. I guess you could extend that attribute to types as well.

In your example, JSONObject casts from string would implicitly trigger the behavior in IDE.

@khalidabuhakmeh @bitbonk @dotnet yeah, I’m just wishcoding a full C# language/compiler feature here.

If I’ve got a string literal in my code which my IDE is guaranteeing contains valid JSON, I’d love to have the compiler back that guarantee up too. And if it’s *validating* it, why not also manifest it as a more interesting object than a mere ‘string’ while you’re at it? Like:

Date christmas = $Date”2022/12/25”;

With compile time warnings, and no runtime parse…

@james_a_hart @bitbonk @dotnet a source generator could do this (I think).

@khalidabuhakmeh @bitbonk @dotnet I suspect so.

There goes my weekend.

@james_a_hart @khalidabuhakmeh @dotnet I doubt that a source generator can do the “manifesting in a more interring object” part but it sure could validate the content of a string literal. But be careful: This type of analysis can become expensive and may degrade the overall IDE performance. Source generators are executed upon every keystroke (with all kinds of optimizations of course).
@bitbonk @james_a_hart @dotnet the source generator can both generate the methods and then read the string literals causing build failures. A Roslyn analyzer might be smarter though tbh.