field initializer cannot reference non static field.method, or property

Answered field initializer cannot reference non static field.method, or property

  • Wednesday, March 07, 2012 3:24 AM
     
      Has Code



    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
     
     Answered
    Just don't do it like that.  Do that in the constructor.

    Jose R. MCP

  • Wednesday, March 07, 2012 5:53 AM
     
     Answered Has Code

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

       QQ我:讨论(Talk)
    下载MSDN桌面工具(Vista,Win7)
    我的博客园
    慈善点击,点击此处

  • Thursday, March 08, 2012 2:00 AM
    Moderator
     
     Answered
    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