0

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
  • 1
    List<T>[] is an array though, and that's what he wrote in his code. Could you explain further what exactly you're talking about? Commented Jan 5, 2021 at 17:31
  • @Blindy Your right, I am blind, that is in fact an array of List<int>. Commented Jan 5, 2021 at 17:32

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.