So I am new to C#, and I am trying to to figure out what the problem is with my code. I know this works in VB.Net just not sure why it doesn't in C#

private Connection myConnection = new Connection();
        private SqlConnection mySqlConnection = new SqlConnection(myConnection.connectionString);

I am getting an error saying "A field initializer cannot reference the non-static field, method, or property" on:

new SqlConnection(myConnection.connectionString);

I am confused as to why it will not work in C#. Thanks in advance for any help.

Edited 6 Years Ago by firebirds98: n/a

You cannot use an instance field to initialise another instance field.
If you definitely want the connection to be an instance field, you can declare them as instance fields then initialise them in the class constructor:

Public Class MyClass {
   
    private Connection myConnection = new Connection();
    private SqlConnection mySqlConnection;

   public MyClass()
   {
      mySqlConnection = new SqlConnection(myConnection.connectionString);
   }

}

So I am new to C#, and I am trying to to figure out what the problem is with my code. I know this works in VB.Net just not sure why it doesn't in C#

private Connection myConnection = new Connection();
        private SqlConnection mySqlConnection = new SqlConnection(myConnection.connectionString);

...

I'm surprised this works in VB.Net since you didn't define the connection string...(OK, I'm assuming you didn't supply that as part of the code.) If you are hard-coding the connection string, you should be able to create a static const string str = ""; and use that.
(It is better to use the constructor as suggested.)

You cannot use an instance field to initialise another instance field.
If you definitely want the connection to be an instance field, you can declare them as instance fields then initialise them in the class constructor:

Public Class MyClass {
   
    private Connection myConnection = new Connection();
    private SqlConnection mySqlConnection;

   public MyClass()
   {
      mySqlConnection = new SqlConnection(myConnection.connectionString);
   }

}

This Works, Thank you!

This article has been dead for over six months. Start a new discussion instead.