I have recently learned C# fully, approximately. However, in C++ I could implement a better encapsulation when passing objects to methods, with const modifier. But in C#, objects can be modified through the reference parameter, such as Dispose on Graphics object.
I need sometimes more encapsulation. Properties can give a better solution. However, I have found that, for example, the modification to Form.Location property or even to its X member is not allowed. Although Form.Location is get; set; property, its members can not be modified. I tried to do as it with a Point {get; set;} property but I can still modify X member.
This is also an issue when a method for example Disposes an object, as eariler mentioned.
How can I implement more encapsulation in C#?
You cannot the
Xproperty ofForm.Location, becauseForm.Locationis a property that returns a value type (Point). As soon as you accessForm.Location, you get a copy of the location; thus, changing something in this copy is meaningless. Sincethis.Location.X = ...is an obvious mistake, the C# compiler prevents you from doing it.You can, however, replace the complete value of
Form.Location, since its property setter ispublic:or, alternatively,
To get back to your original question: If you want to make an object accessible, but do not want it to be modified, you will need to encapsulate it yourself. For example, if you want the consumers of your class to be able to
Drawon yourGraphicsobject but do not want them to callDispose, just cannot expose theGraphicsobject directly. Instead, you need to wrap every method that the consumer is allowed to call: