Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make objects returned by a function immutable in C#?

I am writing a function that returns a reference to an object of some encapsulated data structure and I want nobody to be able to change the object using that reference, is it possible to do this in c#?

like image 515
Ristovak Avatar asked Aug 08 '10 11:08

Ristovak


People also ask

When should an object be immutable?

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

What is an example of immutability?

String is an example of an immutable type. A String object always represents the same string. StringBuilder is an example of a mutable type. It has methods to delete parts of the string, insert or replace characters, etc.

What is a immutable object in programming?

In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

What is the purpose of immutability?

Immutability allows you to track the changes that happen to these objects like a chain of events. Variables have new references that are easy to track compared to existing variables. This helps in debugging the code and building the concurrent application.


1 Answers

If the object that you are returning is immutable, that will work fine.

If not, you can return a wrapper object that only exposes read-only properties.

like image 134
Oded Avatar answered Sep 28 '22 05:09

Oded