Paul Kapustin
Paul Kapustin

Reputation: 3293

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.

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

Upvotes: 4

Views: 4983

Answers (4)

Chris Brandsma
Chris Brandsma

Reputation: 11736

Do you really need operator overloading? We are talking about syntactic sugar here. Also, not all .NET languages utilize operator overloading in the same way. So, if you use operator overloading, you are effectively making your code language-specific.

I would implement the read-only interface and drop the operator overloading requirement.

Upvotes: 3

Paul Kapustin
Paul Kapustin

Reputation: 3293

If anyone is interested in what I did, I finally went for an abstract class instead of interface, and I did hide the method in the derived class to get the right accessors:

Like, in the base abstract class (readonly interface):

protected double accuracy;
public double Accuracy { get { return accuracy; } }

In the derived class:

public new double Accuracy
{
    get { return accuracy; }
    set { accuracy = value; }
}

Of course, ugly with the "new" keyword, but in this case it will do for me.

Upvotes: 1

Vilx-
Vilx-

Reputation: 107072

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.

Upvotes: 4

frankodwyer
frankodwyer

Reputation: 14048

You could implement the readonly behaviour via state in the object, and throw an exception if a modifying method is called?

Upvotes: 2

Related Questions