Problem with initializing an array of List<int> with Initialize method

51 Views Asked by At

I want to implement a graph with an array of List<int>, but when I try to initialize the entries with Array.Initialize() with the default values (by calling a parameterless constructor of List<int>), it's like the method was never called and after that all entries are still null!

int n = int.Parse(Console.ReadLine()); // number of nodes 
List<int>[] g = new List<int>[n]; //graph
g.Initialize();

It's fine when I iterate over the collection and intitialize, but why is there a problem with the method Initialize()?

2

There are 2 best solutions below

0
Blindy On

Don't use Array.Initialize, ever. Read the documentation on the function, it has an entire page of warnings, including a huge red caution box.

Instead initialize your array as you would any other:

for(int i = 0; i < g.Count; ++i)
    g[i] = new();
0
Navid Golforoushan On

You should change your data-type to int[]=>

var myArray = new int[n];

Or If you need for any reason List you can initializing it as shown in below section=>

var defaultValue=65;
var myListWithDefaultValue = Enumerable.Repeat(defaultValue, n).ToList();