Search code examples
c#classencapsulation

C#: Make a field only modifiable using the class that contains it


I'm sure this has been asked before I just don't know the correct way to word it so I can't find what I am looking for.

I have a class with a field which I want to be able to see from the outside, just not be able to modify it directly..

public class myclass
{
    public int value;
    public void add1()
    {
        value = value + 1;
    }
}

So I would really like to only have the 'value' field modifiable from the method add1() but I still want to be able to see the value of 'value'.

EDIT: I was thinking only modifiable via the class myclass, but I typed otherwise. Thanks for pointing that out.


Solution

  • Please consider the following options to encapsulate a field (i.e. provide an "interface" for the private field value):

    1. Provide the public method (accessor):

      // ...
      private value;
      // ...
      public void Add()
      {
          ++value;
      }
      
      public int GetValue()
      {
         return value; 
      }
      
    2. Provide the public property (only accessor):

      // ...
      private value;
      // ...
      
      public void Add()
      {
          ++value;
      }
      
      public int Value
      {
         get { return value; }
      }
      
    3. Provide the auto-implemented property (public accessor, private mutator):

      // ...
      // The field itself is not needed: private value;
      // ...
      
      public void Add()
      {
          ++Value;
      }
      
      public int Value { get; private set; }
      

    It is worth noting that some IDEs or IDE–plugins provide the appropriate refactoring called "Encapsulate Field".