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?