sjantke
sjantke

Reputation: 595

Use AddRange for a new List<string>

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

Upvotes: 2

Views: 2143

Answers (4)

Dennis_E
Dennis_E

Reputation: 8904

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

Upvotes: 1

Christoph Fink
Christoph Fink

Reputation: 23113

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.

Upvotes: 2

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

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

Upvotes: 7

HABJAN
HABJAN

Reputation: 9328

You can simply change your code to this:

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

Upvotes: 5

Related Questions