Question

I know it might not be worth it but just for education purposes I want to know if there is a way to inject your own keywords to .NET languages.

For example I thought it's good to have C++ asm keyword in C#.
Remember I'm not talking about how to implement asm keyword but a general way to add keyword to C#.

My imagined code :

asm{
    mov ax,1
    add ax,4
}

So is there a way to achieve this ?
The answers which cover implementing keyword{ } suits enough for this question.

Was it helpful?

Solution

This isn't possible at the moment. However, there's a Microsoft project in development called Roslyn that can be summarised as "the compiler as a service." It allows you, amongst other things, to extend or modify the behaviour of the compiler through an API.

When Roslyn becomes available, I believe this should be something that (with caution!) is quite doable.

OTHER TIPS

You can use whatever tools you would like to pre-process your code before sending it to the C# compiler. For example, you might use VS macros to do the pre-processing, mapping a given syntax that you invented into something that does compile into C# code, possibly generating an error if there is a problem. If VS macros aren't powerful enough for you then you can always use your own IDE that does whatever you code it to do to the text before sending it to the compiler.

There is no built in support in the compiler for specifying your own keywords/syntax; you would need to handle it entirely independent of the compiler.

Unfortunately this is not possible. You can't extend or alter the languages in any way.

You could in some obscure way use PostSharp to read and parse strings and transform them to custom code at compile time (a pre processor). But you would not get very happy with that, as it is very error prone and you won't get any kind of intellisense or code completion for your magic strings.

According to MSDN keywords are predefined and cannot be altered. So you can't add any, because you would need to tell the compiler how to handle them. Insofar, no you can't.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top