private MyType _member;
public MyType GetMember() { return _member; }
public void SetMember(MyType value) { _member = value };
This is the basic way to protect a private member with public getter and setter methods (a property). Regardless of how you define a property, this is the C# equivalent of what will be created in MSIL. That's also why you will have the value
keyword available in the setter. Every other method is merely syntactic sugar.
The Options are:
// Option 1
public MyType Member { get; set; }
// Option 2
private MyType _member;
public MyType Member
{
get
{
return _member;
}
set
{
_member = value;
}
}
// Option 3
public MyType Member
{
get => _member;
set => _member = value;
}
// Option 4
public MyType Member => _member; //Only a getter, yet even shorter.
What you can do, is not define a setter, this means you can't do an assignment with the property outside like Member = new MyType()
. However, you are still able to access any methods from the outside, that in turn change the value of the underlying data-structure like in Member.Clear()
. Like @Ruzihm pointed out in his excellent answer, you would have to do object-Copying to provide an "uninteractive" copy, that provides "full" protection of the original.