Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A field initializer cannot reference the non-static field, method, or property

Ok so I have the code below, technically all it does is read the db.txt file line by line and then its suppose to split the line 0 into an array called password.

private string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
private string[] password = lines[0].Split(' ');

but I get the error:

A field initializer cannot reference the non-static field, method, or property

like image 512
Ahoura Ghotbi Avatar asked Mar 26 '26 23:03

Ahoura Ghotbi


1 Answers

Have a think about what the above means and how you want to populate those variables. You'd need to first construct the class they are a member of, and then hope the lines of code get executed in the order you want them to, and that they don't throw an exception.

The compiler is effectively telling you this isn't the right way to do things.

A better way is to simply write a function to do what you want:

private string[] PasswordLines(){
  string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
  return lines[0].Split(" "); 
}

You can then call this from anywhere you wanted to; for example:

public class MyClass()
{
 private string[] Lines 
 {
   get { return PasswordLines(); }
 }

 private string[] PasswordLines(){
  string[] lines = System.IO.File.ReadAllLines(@"U:\Final Projects\Bank\ATM\db.txt");
  return lines[0].Split(" "); 
 }

}
like image 152
dash Avatar answered Mar 29 '26 11:03

dash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!