field initializer cannot reference non static field.method, or property
-
Wednesday, March 07, 2012 3:24 AM
class GenralClass { public String id; public int profile; StreamReader Sdr=new StreamReader(Application.StartupPath +" /connection.txt"); public SqlConnection con = new SqlConnection(Sdr.ReadLine()); }
In above line
(Sdr.ReadLine())
as error shown "field initializer cannot reference non static field.method, or property"
Mankatha
All Replies
-
Wednesday, March 07, 2012 4:38 AM
Just don't do it like that. Do that in the constructor.Jose R. MCP
- Marked As Answer by Helen ZhouModerator Friday, March 09, 2012 3:18 AM
-
Wednesday, March 07, 2012 5:53 AM
public SqlConnection con = new SqlConnection(Sdr.ReadLine());
No。Generally speaking,you can call a method that belongs to an instance only in methods,So you should call this in a constructor of the class itself。Try this:
namespace MyTest
{
public class A
{
class Program
{
private String id;
private int profile;
StreamReader Sdr = new StreamReader("connection.txt");
private SqlConnection con = null; //Suggest you create a property for that, don't apply "public"
//on public properties directly……
public Program()
{
con = new SqlConnection(Sdr.ReadLine());
}
}
}
}- Marked As Answer by Helen ZhouModerator Friday, March 09, 2012 3:19 AM
-
Thursday, March 08, 2012 2:00 AMModerator
Hi Mankatha,
The question has been answered in your duplicated case: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/bde06ced-de6e-4849-92b3-15f33cb53f9b
Sincerely,Helen Zhou [MSFT]
MSDN Community Support | Feedback to us
- Marked As Answer by Helen ZhouModerator Friday, March 09, 2012 3:19 AM



