0

I want to express my intent as clear as possible. The method ChangeFields below is allowed to change the object's fields. How about the opposite in which I want to prevent another method, namely ReadOnly from changing the fields?

I know that by default method arguments are immutable -- we cannot change the argument to point to another object -- unless we explicitly use the keyword ref.

class Foo
{
    public string Text;
    public int Count;

    public override string ToString()
    {
        return $"Count = {Count}, Text = {Text}";
    }

    public void Display()
    {
        Console.WriteLine(this);
    }
}




class Program
{
    static void ChangeFields(Foo f)
    {
        f.Count = 10;
        f.Text = "Changed";
    }

    static void ChangeObject(ref Foo f)
    {
        f = new Foo { Text = "New object", Count = 100 };
    }

    static void Main(string[] args)
    {
        Foo f = new Foo { Text = "New", Count = 1 };
        f.Display();

        ChangeFields(f);
        f.Display();

        ChangeObject(ref f);
        f.Display();
    }
}

Question

Is there any trick to explicitly express my intent to prevent a method from changing its object's fields?

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • Do you mean something like `const` in C++? – Louis Go Mar 20 '20 at 06:29
  • @LouisGo: I am not familiar enough with C++, your guess might be correct. – Second Person Shooter Mar 20 '20 at 06:30
  • You want an explicit expression to tell api user or api developer "This method doesn't change parameter"? Answers to these two use cases might be varied. – Louis Go Mar 20 '20 at 06:31
  • There’s no way to stop some method from changing fields while another is allowed. You could do *none* or *all* by with or without `readonly` keyword. – weichch Mar 20 '20 at 06:32
  • 1
    This this answering your question? https://stackoverflow.com/a/3826657/4123703 – Louis Go Mar 20 '20 at 06:35
  • If you have the public properties/fields in you class, that means they can be rear and changed from anywhere. You can not control the behaviour of the method when you are calling it. If `ChangeFields` method is going to be written by you then you should have it accept `Text` and `Count` parameters. Not the `Foo` parameter. And then you can call this method by doing `ChangeFields(f.Text, f.Count)`. – Chetan Mar 20 '20 at 06:38

1 Answers1

0

You can do something like this

class Foo
{
    public string Text { get; private set;} // This mean only method in Foo can change
    public int Count { get; } // This mean can't change this
}