Can we write our own language constructs in C #?

I would like to know whether it is possible to implement in C # my own language constructs (for example, lock or foreach)?

The idea is that I want to mark the beginning and end of a block of operations. instead of writing

startblock("blockname");
  blabla();
  andsoon();
endblock();

I would like to write something like

block("blockname"){
  blabla();
  test();
}

Thank you!

+3
source share
4 answers

Why do you need this? Just for clarity and clean code? C # is not an extensible language. With the help you can achieve this beautifully:

using (new Context("block name"))
{
    // do your staff here
}

class Context : IDisposable
{
    public Context(string name)
    {
        // init context
    }

    public void Dispose()
    {
        // finish work in context
    }
}
+8
source

Another option is to pass the function to the handler.

private void block(string name, Action action)
{
    startblock(name);
    action();
    endblock();
}

The following are:

block("blockname", () =>
                {
                    blabla();
                    test();
                });

Keep in mind that this may be a sign that you need an abstract class (or a regular base class) and allow overriding of this method.

+9
source

Nemerle provides such designs. This is not too different from C #.

+1
source

Source: https://habr.com/ru/post/1761276/


All Articles