Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerable.Repeat for reference type objects initialization

I have a question about Enumerable.Repeat function.

If I will have a class:

class A
{
//code
}

And I will create an array, of that type objects:

A [] arr = new A[50];

And next, I will want to initialize those objects, calling Enumerable.Repeat:

arr = Enumerable.Repeat(new A(), 50);

Will those objects have the same address in memory? If I will want to check their hash code, for example in that way:

bool theSameHashCode = questions[0].GetHashCode() == questions[1].GetHashCode();

This will return me true, and if I will change one object properties, all other objects will change it too.

So my question is: is that properly way, to initialize reference type objects? If not, then what is a better way?

like image 319
Michael Avatar asked Jul 05 '17 22:07

Michael


People also ask

How to use Enumerable repeat in c#?

The following code example demonstrates how to use Repeat to generate a sequence of a repeated value. ' Repeat the same string to create a sequence. Dim sentences As IEnumerable(Of String) = Enumerable. Repeat("I like programming.", 15) Dim output As New System.

What is enumerable repeat?

Enumerable. Repeat method is part of System. Linq namespace. It returns a collection with repeated elements in C#. Firstly, set which element you want to repeat and how many times.


2 Answers

Using Enumerable.Repeat this way will initialize only one object and return that object every time when you iterate over the result.

Will those objects have the same address in memory?

There is only one object.

To achieve what you want, you can do this:

Enumerable.Range(1, 50).Select(i => new A()).ToArray();

This will return an array of 50 distinct objects of type A.

By the way, the fact that GetHashCode() returns the same value does not imply that the objects are referentially equal (or simply equal, for that matter). Two non-equal objects can have the same hash code.

like image 86
Kapol Avatar answered Oct 02 '22 20:10

Kapol


Just to help clarify for Camilo, here's some test code that shows the issue at hand:

void Main()
{
    var foos = Enumerable.Repeat(new Foo(), 2).ToArray();
    foos[0].Name = "Jack";
    foos[1].Name = "Jill";
    Console.WriteLine(foos[0].Name);    
}

public class Foo
{
    public string Name;
}

This prints "Jill". Thus it shows that Enumerable.Repeat is only creating one instance of the Foo class.

like image 37
Enigmativity Avatar answered Oct 02 '22 18:10

Enigmativity