0

I'm going to make library managment application. but at the begining stage I have an error called, "A field initializer cannot reference the non-static field, method, or property 'ProjectRI.ClassesAndInterfaces.StudentClass.x'"

I have class called 'DbClass';

class DBclass
{
    private static String conString = @"server=localhost;user id=root;persistsecurityinfo=True;database=royalinstitute";

    public String ConString
    {
        get { return conString; }
        set { conString = value; }
    }
}

My connection string in this 'DbClass', so it can change easily and also the conString variable can use just by creating an object.. And that field is encapsulated.

I have another class called 'StudentClass';

class StudentClass
{
    DBclass x = new DBclass();
    MySqlConnection conn = new MySqlConnection(x.ConString);

    public void add() 
    { 
    }

    public void update()
    {
    }

    public void remove()
    {
    }
}

The error in this StudentClass. That is, i cannot access 'conString' field in my 'DbClass' by creating an object 'x'.

MySqlConnection conn = new MySqlConnection(x.ConString);

The error is above line, "Error 1 A field initializer cannot reference the non-static field, method, or property"

Please help me to fix this..

Indunil Girihagama
  • 415
  • 1
  • 7
  • 11

2 Answers2

0
class StudentClass
{
    DBclass x = new DBclass();
    MySqlConnection conn=  null;

    public StudentClass()
    {
        conn = new MySqlConnection(x.ConString);
    }

    public void add()
    {
    }

    public void update()
    {
    }

    public void remove()
    {
    }
}
dotnetstep
  • 17,065
  • 5
  • 54
  • 72
0

Make the property static :

public static String ConString
{
    get { return conString; }
    set { conString = value; }
}

Use it with : MySqlConnection conn = new MySqlConnection(DBClass.ConString);

Sievajet
  • 3,443
  • 2
  • 18
  • 22