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.

Recommended Answers

All 5 Replies

have you placed those lines of code inside a method?

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!

No problem :) Remember to mark the thread as solved if your question has been answered

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.