473,322 Members | 1,425 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

immutable

how do you create an immutable object in c#?

thanks in advance
Nov 1 '06 #1
16 5623

An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:

class IdNamePair {
private int id;
private string name;

public IdNamePair(int id, string name) {
this.id = id;
this.name = name;
}

public int Id { get { return id; } }
public string Name { get { return name; } }
}

Is immutable because there is no way to change id or name once they've
been set on the constructor. 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.

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

On Wed, 1 Nov 2006 18:50:18 -0000, "fallenidol"
<fa********@discussions.microsoft.comwrote:
>how do you create an immutable object in c#?

thanks in advance
Nov 1 '06 #2
Hi,

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).

Cheers,
IGnacio

"fallenidol" wrote:
how do you create an immutable object in c#?

thanks in advance
Nov 1 '06 #3
Hi,

>
An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:
No really, if you have method that changes the instance members the class
is not inmutable.

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.

As a matter of fact that maybe the only way to really be sure that the class
will be inmutable.
And even so there is no enforcement of that. The above works for valued
types. In the case of the references you can only assure that the reference
will not chage. There is no way to enforce that the referenced instance does
not change.
Nov 1 '06 #4
On Wed, 1 Nov 2006 11:31:02 -0800, ignacio machin
<ig***********@discussions.microsoft.comwrote:
>Hi,

>>
An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:

No really, if you have method that changes the instance members the class
is not inmutable.

And where is there a method changing the immutable value in my
example? As I said, the important part is the value is set in the
constructor and only a read-only property is available to read the
value. Therefore nothing is provided to change the value, hence it's
immutable.

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
Nov 1 '06 #5
string s = "this is an immutable object, because String is immutable";

--
Co-founder, Eggheadcafe.com developer portal:
http://www.eggheadcafe.com
UnBlog:
http://petesbloggerama.blogspot.com


"fallenidol" wrote:
how do you create an immutable object in c#?

thanks in advance
Nov 1 '06 #6
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.

Mike Ober.

"ignacio machin" <ig***********@discussions.microsoft.comwrote in message
news:7A**********************************@microsof t.com...
Hi,

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).

Cheers,
IGnacio

"fallenidol" wrote:
>how do you create an immutable object in c#?

thanks in advance

Nov 1 '06 #7
ignacio machin <ig***********@discussions.microsoft.comwrote:
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).
One thing missed from all of the replies so far is the possibility of
the values in the class not changing, but referenced objects changing.
For instance, is the following class immutable?

class Test
{
IList list = new ArrayList();

public IList List { get { return list; } }
}

You can't change which list an instance refers to, but you can change
the contents of the list.

(Similarly, even if a property returns a value type, if that value type
contains a mutable reference type you could observe a change.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 1 '06 #8
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.
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
ignacio machin <ig***********@discussions.microsoft.comwrote:
>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).

One thing missed from all of the replies so far is the possibility of
the values in the class not changing, but referenced objects changing.
For instance, is the following class immutable?

class Test
{
IList list = new ArrayList();

public IList List { get { return list; } }
}

You can't change which list an instance refers to, but you can change
the contents of the list.

(Similarly, even if a property returns a value type, if that value type
contains a mutable reference type you could observe a change.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Nov 1 '06 #9
Hi,

And once you "get it", you can add to it:

Test test = new Test();
IList list = test.List;
list.Add(new object());
int c = list.Count;

// c = 1

You might have thought that the "test" variable was immutable because it only
contains a single, read-only property; However, it exposes a mutable
reference, making test itself mutable:

// use test.List again
list = test.List;
list.Add(new object());
c = list.Count;

// c = 2

Because test.List returns the same, mutable reference each time, the Count
will continue to increase when objects are added to the test.List.

--
Dave Sexton

"fallenidol" <fa********@discussions.microsoft.comwrote in message
news:e3*************@TK2MSFTNGP02.phx.gbl...
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.
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
>ignacio machin <ig***********@discussions.microsoft.comwrote:
>>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).

One thing missed from all of the replies so far is the possibility of
the values in the class not changing, but referenced objects changing.
For instance, is the following class immutable?

class Test
{
IList list = new ArrayList();

public IList List { get { return list; } }
}

You can't change which list an instance refers to, but you can change
the contents of the list.

(Similarly, even if a property returns a value type, if that value type
contains a mutable reference type you could observe a change.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


Nov 1 '06 #10
KH
You can't change the object that 'list' points at, but you can change the
contents of the list...

Test t = new Test();
Console.WriteLine( t.List.Count ); // Zero
t.List.Add(0);
Console.WriteLine( t.List.Count ); // One
"fallenidol" wrote:
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.
"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP************************@msnews.microsoft.c om...
ignacio machin <ig***********@discussions.microsoft.comwrote:
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).
One thing missed from all of the replies so far is the possibility of
the values in the class not changing, but referenced objects changing.
For instance, is the following class immutable?

class Test
{
IList list = new ArrayList();

public IList List { get { return list; } }
}

You can't change which list an instance refers to, but you can change
the contents of the list.

(Similarly, even if a property returns a value type, if that value type
contains a mutable reference type you could observe a change.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too


Nov 1 '06 #11
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.
"Samuel R. Neff" <sa********@nomail.comwrote in message
news:sr********************************@4ax.com...
On Wed, 1 Nov 2006 11:31:02 -0800, ignacio machin
<ig***********@discussions.microsoft.comwrote:
>>Hi,

>>>
An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:

No really, if you have method that changes the instance members the
class
is not inmutable.


And where is there a method changing the immutable value in my
example? As I said, the important part is the value is set in the
constructor and only a read-only property is available to read the
value. Therefore nothing is provided to change the value, hence it's
immutable.

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.

Nov 2 '06 #12
Hi,

But to be fair, reflection isn't part of the generally acceptable language
constructs used when designing a type-safe application. If you're trying to
design your classes to prevent reflection from changing the values of private
fields, then immutability will probably be the least of your concerns.

For example, you might want to support internal, lazy initialization on a
class but then maintain immutability afterwards. In that case, you won't be
able to mark the fields as read-only. I would still consider the class to be
immutable regardless of the possibility that another class will use reflection
as a means for unsanctioned change, simply because reflection can be used to
cause all sorts of undesirable effects for which you can't prepare ahead of
time.

--
Dave Sexton

"news.microsoft.com" <gustavo_[remove]fr****@hotmail.comwrote in message
news:uB**************@TK2MSFTNGP04.phx.gbl...
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.
"Samuel R. Neff" <sa********@nomail.comwrote in message
news:sr********************************@4ax.com...
>On Wed, 1 Nov 2006 11:31:02 -0800, ignacio machin
<ig***********@discussions.microsoft.comwrote:
>>>Hi,

An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:

No really, if you have method that changes the instance members the class
is not inmutable.


And where is there a method changing the immutable value in my
example? As I said, the important part is the value is set in the
constructor and only a read-only property is available to read the
value. Therefore nothing is provided to change the value, hence it's
immutable.

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.


Nov 2 '06 #13
Hi,

Does your solution protect against direct accessing the memory?
I don't have the idea about that.

I assume we are here talking about normal developing situations and for that
the answer from Samuel is in my idea more than enough.

Cor

"news.microsoft.com" <gustavo_[remove]fr****@hotmail.comschreef in bericht
news:uB**************@TK2MSFTNGP04.phx.gbl...
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.
"Samuel R. Neff" <sa********@nomail.comwrote in message
news:sr********************************@4ax.com...
>On Wed, 1 Nov 2006 11:31:02 -0800, ignacio machin
<ig***********@discussions.microsoft.comwrote:
>>>Hi,

An class whose data is provided in the constructor and has only
read-only properties is immutable. For example:

No really, if you have method that changes the instance members the
class
is not inmutable.


And where is there a method changing the immutable value in my
example? As I said, the important part is the value is set in the
constructor and only a read-only property is available to read the
value. Therefore nothing is provided to change the value, hence it's
immutable.

Sam

------------------------------------------------------------
We're hiring! B-Line Medical is seeking Mid/Sr. .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.


Nov 2 '06 #14
fallenidol <fa********@discussions.microsoft.comwrote:
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.
Test t = new Test();

IList list = t.List;
list.Add (new Object());

That hasn't changed which list the Test instance refers to, but it
changes the contents of the list - so if someone else is using that
Test instance, they can't rely on the contents not changing. That's
pretty much the same as saying it's not immutable.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 2 '06 #15
Michael D. Ober <obermd.@.alum.mit.edu.nospamwrote:
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.
Just to be picky, DateTime is a struct - which fortunately, MS
understood they should make immutable.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 2 '06 #16
news.microsoft.com <gustavo_[remove]fr****@hotmail.comwrote:
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.
What makes you think that making the field readonly would help?

using System;
using System.Reflection;

class Test
{
readonly int x;

public Test (int y)
{
x = y;
}

public int X
{
get { return x; }
}
}

class Entry
{
static void Main()
{
Test t = new Test(10);
Console.WriteLine (t.X);
FieldInfo fi = typeof(Test).GetField("x",
BindingFlags.NonPublic |
BindingFlags.Instance);
fi.SetValue (t, 20);
Console.WriteLine (t.X);

}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 2 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Zalek Bloom | last post by:
I am learning about difference between String and StringBuffer classes. In a book it sayes that a String class is immutable, that means that one an instance of String class is created, the string...
7
by: Torsten Mohr | last post by:
Hi, reading the documentation (and also from a hint from this NG) i know now that there are some types that are not mutable. But why is it this way? From an overhead point of view i think...
48
by: Andrew Quine | last post by:
Hi Just read this article http://www.artima.com/intv/choices.html. Towards the end of the dicussions, when asked "Did you consider including support for the concept of immutable directly in C#...
22
by: Ben Finney | last post by:
Howdy all, I've recently packaged 'enum' in PyPI. In its description, I make the claim that it creates "immutable" enumeration objects, and that the enumeration values are "constant" values. ...
90
by: Ben Finney | last post by:
Howdy all, How can a (user-defined) class ensure that its instances are immutable, like an int or a tuple, without inheriting from those types? What caveats should be observed in making...
3
by: Sam Kong | last post by:
Hi group, I want to have some advice about immutable objects. I made a constructor. function Point(x, y) { this.x = x; this.y = y; }
16
by: InDepth | last post by:
Now that .NET is at it's fourth release (3.5 is coming soon), my very humble question to the gurus is: "What have we won with the decision to have string objects immutable? Or did we won?" ...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.