Miguel
Miguel

Reputation: 3496

Is this a good practice of immutability?

Good morning,

Suppose I have a class

public class Class
{
    int something;
    int[] otherThing;
}

and I want to make objects of type Class immutable. Suppose also that I have a very frequent operation which creates a new object of type Class,

public Class SomeFunction()
{
    int[] Temp = new int[] { ... };

    return new Class(1, Temp);
}

To avoid creating new objects too often, and since Tempis no longer accessible out of the method, is it too bad to set on the constructor

this.otherThing = Temp;

instead of

otherThing = new uint[Temp.Length];

for (int i = 0; i < Temp.Length; i++)
{
    this.otherThing[i] = Temp[i];
}

?

Thank you very much.

Upvotes: 0

Views: 154

Answers (3)

Unmesh Kondolikar
Unmesh Kondolikar

Reputation: 9312

It is better to assign a copy of temp to otherThing so that any changes to otherThing will not change temp. You can also use the Array.CopyTo method for this purpose.

In addition you should seriously consider using IEnumerable<int> or IList<int> instead of int[] because arrays by nature work against the idea of immutability. Read this blog post by Eric Lippert.

Upvotes: 2

CodesInChaos
CodesInChaos

Reputation: 108800

If the constructor that does this is private its fine IMO. Since you know the content of the other array will never change you can directly use it. You could even share one instance of the array between several instances of your class if you want to without causing any problems.

A public constructor directly using a provided array is a bad idea on the other hand. Since that can be used to break immutability.

Upvotes: 3

Geniedesalpages
Geniedesalpages

Reputation: 418

The difference is that in the first option you always get a new instance and in the second one all the created "Class"es will point to the same array (!). So if you change something in the array in any Class, all the other classes are changed.

Upvotes: 0

Related Questions