Custom compound statements in C #

I would like to write my own custom compound statements that have a similar mechanism for mechanisms usingand lockwhere they have the code introduced at the beginning and at the end of the statement block before compilation.

I tried to find answers to questions that might have asked similar questions, but I could not correctly understand what kind of code is called, except for documentation saying that these are complex statements.

I know that “blocking” and “using” are keywords. I do not want to have my own keywords, because I know that this is not possible.

Not sure if this is possible in C #, for example:

Instead of doing:

StartContext(8);
//make method calls
EndContext();

This can be reduced to:

DoSomethingInContext(8) {
    //make method calls
}

, . , .

+4
2

:

DoSomethingInContext(8, () => {
    // make method calls
});

:

public void DoSomethingInContext(int contextId, Action contextBoundAction)
{
    // start/open/enter context
    try
    {
        contextBoundAction();
    }
    finally
    {
        // stop/close/exit context
    }
}

, , , IDisposable, , intellisense ( ) Visual Studio ReSharper . DoSomethingInContext, , . IDE, Xamarin Studios, ( ).

- , .

+8

, using. Dispose, :

public class MyWrapper: IDisposable
{
    int _id;

    public MyWrapper(int id)
    {
        _id = id;
        Debug.WriteLine("Begin " + _id);
    }

    public void Dispose()
    {
        Debug.WriteLine("End " + _id);
    }
}

:

using(new MyWrapper(id))
{
    Debug.WriteLine("Middle " + id);
}

DotNetFiddle


, , - (, Push Pop DrawingContext) - finally.

+6

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


All Articles