Restrict use of instance variable to single method in C#

332 Views Asked by At

I want to be able to restrict usage of a instance variable to one method, and other usages should not be possible (compile error, or warning). For instance

public class Example
{
    public string Accessor()
    {
        if (SuperPrivate == null) // allowed
        {
            SuperPrivate = "test"; // allowed
        }

        return SuperPrivate; // allowed
    }

    private string SuperPrivate;

    public void NotAllowed()
    {
        var b = SuperPrivate.Length; // access not allowed
        SuperPrivate = "wrong"; // modification not allowed
    }

    public void Allowed()
    {
        var b = Accessor().Length; // allowed
        // no setter necessary in this usecase
    }
}

Usage of Lazy, automatic properties, or encapsulation in a separate object is not possible. I thought about extending ObsoleteAttribute, but it's sealed.

1

There are 1 best solutions below

1
Marc Gravell On BEST ANSWER

That's not a thing that you can do out of the box. You could write a custom Roslyn analyzer that checks, for example, for an attribute of yours and adds a warning/error, but writing Roslyn analyzers is not trivial. It isn't entirely hard, either, note.

Consider:

// TODO: add an analyzer that checks for this attribute and applies the enforcement
[RestrictAccessTo(nameof(Accessor), nameof(Allowed))]
private string SuperPrivate;