Search code examples
c#visual-studioasp.net-coreerror-handling

Check if variable is being modified within a class


My code:

public int Position
{
    get
    {
        return position;
    }
    private set
    {
        position = value;
    }
}

Currently 'Position' cannot be modified outside the class.

When I do

MyClass.Position = 1

Visual Studio gives me the error The property or indexer 'MyClass.Position' cannot be used in this context because the set accessor is inaccessible. Is there a way to change the code such that I can check if the variable is being modified within the class or outside of class and throw new InvalidOperationException if the variable is being changed outside of the class?

I want to throw the error myself instead of Visual Studio stopping me.

Thank you in advance!


Solution

  • You could make a "internal_set" flag and set to true when you set value internally.

        public class MyClass
        {
            private int position;
            private bool internal_set = false;
            public int Position 
            {
                get
                {
                    return position;
                }
                set
                {
                    if (internal_set)
                    {
                        position = value;
                        internal_set = false;    //set flag back to false;
                    }
                    else
                    {
                        throw new InvalidOperationException();
                    }
                }
            }
            public void set()
            {
                internal_set = true;  //You need set the flag to true before set value;
                Position = 1;
            }
        }