Method and Property decorators

Topics: C# Language Design
Sep 20, 2014 at 12:07 PM
Edited Sep 20, 2014 at 12:10 PM
Add Method decorators like in Phyton for changing Method IL by decorator in compile time after compiler generates method IL.

For example:
class PreconditionDecoratorAttribute( Type type, String methodName ) : DecoratorAttribute
{
    protected override Decorate( MethodBody body )
    {
        type.GetMethod( methodName ).Invoke( new[] { body } );
    }
}

static class Preconditions
{
    public static void ParametersNullCheck ( MethodBody body )
    {
        //insert parametersNullCheck In Method
    }
}
...

[PreconditionDecorator(typeof(Preconditions), nameof(Preconditions.ParametersNullCheck))]
void SomeMethod( SomeType obj, String key )
{
    some work
}

//or
class ParameterNullCheckDecoratorAttribute( ) : DecoratorAttribute
{
    protected override Decorate( MethodBody body )
    {
        Preconditions.ParametersNullCheck ( body );
    }
}

[ParameterNullCheckDecorator]
void SomeMethod( SomeType obj, String key )
{
    some work
}
It will be useful for testing purposes too:
[DecoratorUesage( ApplyFor = "TEST", DecorateType = DecorateType.DeepCallHierarchy, DecorationType = DecorationType.CopyMethod )] //DecorateCopyOfMethod and call methods so source method will be preserved for another tests
class TestDecoratorAttribute(...): DecoratorAttribute
{
     protected override Decorate( MethodBody body )
     {
         // Change some members to Mocks and Call Mocked Type with mocked parameters...
         // Full Mocking and Testing abilities in language no need third party tool that inject dlls after compile
     }
}
...
void SomeSophisticatedMethod( NonInterfaceType obj )
{
    ...
    SomeStatic.GetSomething( obj, ... );
    ...
}
...

[TestDecorator(...)] //Change method calls and object to some mocks
void SomeSophisticatedMethodTest()
{
    ...
    SomeSophisticatedMethod( NonInterfaceType obj, ... );
    ...
}