F
fallenidol
how do you create an immutable object in c#?
thanks in advance
thanks in advance
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:
You can and should also specify readonly
on the field declarations but I wanted to leave that out here to
reinforce that the read-only properties are what make this class
immutable.
Hi,
No really, if you have method that changes the instance members the class
is not inmutable.
ignacio machin said:There is nothing in the language that check if a class you intended to make
inmutable is in reality inmutable.
Currently inmutable is more like a concept, it's simply a class that its
state does not change after it was initialized.
It's up to you do enforce it. You can only have "get" properties and none
method can have a side effect ( change the internals members).
fallenidol said:mmm i cannot see anyway of changing 'list' in your example. its created as
an empty arraylist and then all you can do i get it.
fallenidol said:mmm i cannot see anyway of changing 'list' in your example. its created as
an empty arraylist and then all you can do i get it.
fallenidol said:mmm i cannot see anyway of changing 'list' in your example. its created as
an empty arraylist and then all you can do i get it.
Michael D. Ober said:As a side issues, all methods and properties on the class need to be coded
to avoid changing the contents of the class and they need to return a new
instance of the class. This allows, in the case of System.String
string s = "This is an example "
string r = s.Trim().ToUpper()
"r" now contains "THIS IS AN EXAMPLE"
"s' now contains "This is an example "
The system.DateTime class is another example of this type of functionality.
news.microsoft.com said:Anyway if you want to be sure the "primitves" values inside the class are
immutable, they should be declared as readonly, because a property with just
a get is not enough.
Reflection allows to change private member values even if the class doesn't
expose set properties.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.