UpTide
UpTide

Reputation: 358

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.

Upvotes: 1

Views: 1270

Answers (3)

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".

Upvotes: 2

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

You can use public property without setter to just see the value from outside. make the value private so its only visible inside the calss.

public class myclass
{
    private int value;
    public void add1()
    {
        value = value + 1;
    }
    public int Value
    {
       get
       {
           return value; 
       }
    }
}

Upvotes: 2

Rob
Rob

Reputation: 27357

public int value { get; private set; }

You cannot make it modifiable only by the method add1, but you can make it only modifiable by myclass.

See this:

https://msdn.microsoft.com/en-us/library/75e8y5dd.aspx

Upvotes: 5

Related Questions