Is it good/bad practice to do the following: public class MyClass { public MyTyp
ID: 642892 • Letter: I
Question
Is it good/bad practice to do the following:
public class MyClass {
public MyType MyProperty { get; private set; }
public void SetMyProperty(MyType myProperty) {
MyProperty = myProperty;
}
}
My intention is to prevent MyProperty from being accidentally changed outside the class. However, it can be changed if needed.
Also, if MyType is a reference type, then will the private set prevent, for example:
instanceOfMyClass.MyProperty.SomeField = 2;
In other words, will it make MyProperty and all its members readonly, or just the reference to MyProperty?
Sorry if this seems an unintelligent question; I'm afraid I'm a beginner.
Explanation / Answer
My intention is to prevent MyProperty from being accidentally changed outside the class. However, it can be changed if needed.
I'm not seeing the point of doing this, to be honest. Calling
myClass.MyProperty = new MyType();
is not any less intentional than calling
myClass.SetMyProperty(new MyType());
In terms of readability, I think you're far better off going with the more intuitive setter approach instead of a separate method. And if you don't want to allow anyone to change the value of MyProperty, then don't allow it either via a setter or a method.
In other words, will it make MyProperty and all its fields readonly, or just the reference to MyProperty?
Just the reference to MyProperty. MyType has to be an immutable type if you want to prevent people from changing its properties.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.