DanB
DanB

Reputation: 41

Control Access to Class Members

I want a specific routine to be able to set a variable within a class - but the field otherwise to remain read-only.

For example the int 'authlevel' here should be publicly accessible to read - but only able to be set by selective subs;

public class SessionAuth
{
    int authLevel;
    public int AuthLevel
    {
        get
            {return authLevel;}

        set
            {<<IF CALLER = SUB XYZ>> then authLevel=value;}

    }
  ...

Is this possible?

Upvotes: 1

Views: 177

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61339

You probably could do this via the diagnostic libraries (that are used to generate call stacks), but you don't want to.

If you need to restrict access to the setter, mark it as private so that only your class can modify it. If you can't trust your own class, you need to re-think your code and design.

public int MyProp { get; private set; }

Upvotes: 4

Related Questions