Is there a way to implement custom language features in C#?

Viewed 11259

I've been puzzling about this for a while and I've looked around a bit, unable to find any discussion about the subject.

Lets assume I wanted to implement a trivial example, like a new looping construct: do..until

Written very similarly to do..while

do {
    //Things happen here
} until (i == 15)

This could be transformed into valid csharp by doing so:

do {
    //Things happen here
} while (!(i == 15))

This is obviously a simple example, but is there any way to add something of this nature? Ideally as a Visual Studio extension to enable syntax highlighting etc.

6 Answers

I found the easiest way to extend the C# language is to use the T4 text processor to preprocess my source. The T4 Script would read my C# and then call a Roslyn based parser, which would generate a new source with custom generated code.

During build time, all my T4 scripts would be executed, thus effectively working as an extended preprocessor.

In your case, the none-compliant C# code could be entered as follows:

#if ExtendedCSharp
     do 
#endif
     {
                    Console.WriteLine("hello world");
                    i++;
     }
#if ExtendedCSharp
                until (i > 10);
#endif

This would allow syntax checking the rest of your (C# compliant) code during development of your program.

Related