2

How to: Use AddRange for a List

List<string> list = 
    new List<string>().AddRange(File.ReadAllLines(path, Encoding.UTF8);

It is a variable which is declared globally - what is my mistake?

The error is equal to

Converting from string to void is not allowed

Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
sjantke
  • 605
  • 4
  • 9
  • 35

4 Answers4

7

cause AddRange return type is void, not List<string>.

And, as error states, you can't assign (=) a void to a List<string>

You can just do

List<string> list = File.ReadAllLines(path, Encoding.UTF8).ToList();
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122
4

You can simply change your code to this:

List<string> list = new List<string>(File.ReadAllLines(path, Encoding.UTF8));
HABJAN
  • 9,212
  • 3
  • 35
  • 59
1

You need to dow it in two steps:

var list = new List<string>();
list.AddRange(File.ReadAllLines(path, Encoding.UTF8));

AddRange does not return the list, so you need to "get the instance first" or directly initialize it like HABJAN suggested.

T.S.
  • 18,195
  • 11
  • 58
  • 78
Christoph Fink
  • 22,727
  • 9
  • 68
  • 113
1

You need to split your statement:

List<string> list = new List<string>();
list.AddRange(File.ReadAllLines(path, Encoding.UTF8));

Or, if you want to do it in 1 step:

List<string> list = File.ReadAllLines(path, Encoding.UTF8).ToList();
T.S.
  • 18,195
  • 11
  • 58
  • 78
Dennis_E
  • 8,751
  • 23
  • 29