Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a readonly (immutable) object interface in C#

My goal is to make sure that in most scenarios objects are used via a "read-only interface" that is a subset of the full interface.

  • As an example, if I were using C++, I would just return a const object.
  • In C#, if I could achieve this with interfaces, I would just implement a read-only interface and use it everywhere. However, I need operator overloading, which is not allowed for interfaces. That's why I have to use an abstract base class.
  • But if I define an abstract base class, I am not allowed to change accessibility in the derived type.

So, how can I achieve my goal in C#?

like image 372
Paul Kapustin Avatar asked Dec 30 '22 07:12

Paul Kapustin


1 Answers

How about if you placed your write operations in an interface and then implement in explicitly on the abstract base class? It would not be a 100% perfect solution (you could still cast the object to the modification interface), but for most part it would prevent anyone from accidentally calling the modifying methods.

like image 99
Vilx- Avatar answered Jan 13 '23 15:01

Vilx-