Skip to content
Pascal Craponne edited this page Oct 8, 2018 · 4 revisions

Introducing fields

Fields introduction is the ability to add fields to target type.
You declare and use them this way:

public class ADummyIntroductionAdvice : Attribute, IMethodAdvice
{
    public IntroducedField<int> MyProperty;

    public void Advise(MethodAdviceContext context)
    {
        // accesses the property
        ++MyProperty[context];
        context.Proceed();
    }
}

However fields above are unique to each advice (each attribute instance). If you want to share introduced fields between advices to the same class, you can use the SharedIntroducedField<TField>:

public class ADummyIntroductionAdvice : Attribute, IMethodAdvice
{
    public SharedIntroducedField<int> MyProperty;

    public void Advise(MethodAdviceContext context)
    {
        // accesses the property
        ++MyProperty[context];
        context.Proceed();
    }
}

You can also introduce static fields (right, I'm not sure when writing those lines that it is very useful):

public class ADummyStaticIntroductionAdvice : Attribute, IMethodAdvice
{
    public static IntroducedField<int> MyStaticProperty;

    public void Advise(MethodAdviceContext context)
    {
        // accesses the static property
        ++MyStaticProperty[null];
        context.Proceed();
    }
}