Is it possible to add a keyword in C # or VB.NET?

I know that this may not be worth it, but only for educational purposes. I want to know if there is a way to implement your own .NET keywords.

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

My imaginary code is:

asm{ mov ax,1 add ax,4 } 

So, is there a way to achieve this?
The answers that cover the implementation of keyword{ } are suitable enough for this question.

+6
source share
4 answers

This is currently not possible. However, there is a Microsoft project called Roslyn , which can be summarized as a "compiler as a service." This allows, among other things, to extend or change the behavior of the compiler through the API.

When Roslin becomes available, I believe that it should be something that (with caution!) Is fully feasible.

+4
source

Unfortunately this is not possible. You cannot extend or modify languages ​​in any way.

You may use PostSharp in some obscure way to read and parse strings and convert them to user code at compile time (preprocessor). But you would not be very happy about this, since it is very error prone, and you will not get any perfection or code completion for your magic lines.

+2
source

You can use any tools that you would like to pre-process your code before sending it to the C # compiler. For example, you can use VS macros for preprocessing by matching this syntax that you invented to something that compiles into C # code, possibly generating an error if there is a problem. If VS macros are not powerful enough for you, you can always use your own development environment, which does everything you code for it before the text before sending it to the compiler.

The compiler has no built-in support for specifying your own keywords / syntax; you will need to fully process it regardless of the compiler.

+2
source

According to MSDN, keywords are predefined and cannot be changed. Therefore, you cannot add them, because you will need to tell the compiler how to handle them. If you can not do it.

0
source

All Articles