0

I want to get the server details from a textdocument, so i passed the parameter (loacalhost) to connectionstring. but the following error occurs.

"A field initializer cannot reference the non-static field"

public partial class Form1: Form
{

    public Form1()
    {
        InitializeComponent();
        labelget();

    }
     string localhost ;
     string myconnectionstring = "Server=" + localhost + "; Database=amepos2015; Uid=root; Pwd=fatehshah";  /*error on this line */

     public void labelget()
     {

             using (StreamReader sr = new StreamReader("C:/Requirement.txt"))
             {
                 while ((localhost = sr.ReadLine()) != null)
                 {
                     localhost = sr.ReadLine();
                 }
             }
         }
         catch (Exception ea)
         {
             if (MessageBox.Show("File not found", "Error", MessageBoxButtons.OK) == DialogResult.OK)
             {
                 Application.Exit();
             }
         }
         Console.Read();
     }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Ameena
  • 187
  • 2
  • 5
  • 18
  • 3
    On which line exactly? Have you _ever_ search your exception message on Google. I think you will find tons of information about that. https://www.google.com/search?q=A+field+initializer+cannot+reference+the+non-static+field – Soner Gönül Feb 17 '15 at 08:47
  • It's just not allowed. Please see: https://msdn.microsoft.com/en-us/library/aa645759%28v=vs.71%29.aspx. You need to move initilization to constructor if you want to do it in such way. –  Feb 17 '15 at 08:48
  • I have mentioned it in the code @soner – Ameena Feb 17 '15 at 08:48

2 Answers2

3

You cannot concat multiple string fields in a class to initialize them because it is not allowed that the variable initializer for an instance field references the instance being created(like other properties or fields) .

Use the constructor instead:

public Form1()
{
    InitializeComponent();

    localhost = "blah ..."; // initialize this string
    myconnectionstring = "Server=" + localhost + "; Database=amepos2015; Uid=root; Pwd=fatehshah";  

    labelget();
}

string localhost = null;
string myconnectionstring = null;

The reason is that the compiler wants to prevent you from errors that would happen if you change the order of the fields. So it's not allowed in the first place.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 2
    The problem is not caused by concatenation. The problem casues accessing the other instance field while field initialization. Reffer: https://msdn.microsoft.com/en-us/library/aa645759%28v=vs.71%29.aspx –  Feb 17 '15 at 08:50
  • @pwas: maybe i haven't found the right words but what is the difference? If he uses string concatenation to initialize one field with another, he is accessing another field which is not allowed. The reason is that the compiler wants to prevent you from errors that will happen if you change the order of the fields. – Tim Schmelter Feb 17 '15 at 08:52
  • @TimSchmelter. Yeah but it could be confusing - so "if concatenation is not allowed it doesn't mean that other operations (like math operations f.e) are not allowed". –  Feb 17 '15 at 08:54
  • @pwas: however, i have added your link and some explaining words. – Tim Schmelter Feb 17 '15 at 08:56
  • @TimSchmelter You asked what is the difference. There is a major difference. If you use constants or static fields, it would have worked. The thing is instance members can't be used there because you can't refer `this` keyword there, because `this` pointer isn't fully initialized. – Sriram Sakthivel Feb 17 '15 at 09:00
  • @SriramSakthivel: i just wondered what is the difference between what pwas has said and what i have said. I've already edited my answer to emphasize this more even if i wanted to say the same from the start. – Tim Schmelter Feb 17 '15 at 09:01
  • @TimSchmelter I disagree with you that *The reason is that the compiler wants to prevent you from errors that will happen if you change the order of the fields*. If that's true, why the stupid compiler doesn't prevent this for static members? You can do the same thing with static members. – Sriram Sakthivel Feb 17 '15 at 09:01
  • @SriramSakthivel: `static` is not related to the current instance so that is not comparable. Of course it is allowed to use static fields or properties or constants since those are not part of the current initialization process. But someone could argue that is should be allowed to refer to other instance fields if they were initialized at this point which is true if they come before(_"The variable initializers are executed in the textual order in which they appear in the class declaration"_). But it is not allowed because it would rely on the declaration order. – Tim Schmelter Feb 17 '15 at 09:05
  • @TimSchmelter I think you got me wrong. if both fields are static, why compiler doesn't prevents me doing this. For static initializers also the execution occurs in textual order, so it suffers from same change of the order issue you're referring. I mean this code will fail `public class SomeClass { private static string someText = obj.ToString(); private static object obj = new object(); }` Why compiler doesn't prevent us from doing this? – Sriram Sakthivel Feb 17 '15 at 09:11
  • @SriramSakthivel: i'm not E.Lippert so i don't know why. Maybe because it is necessary under special circumstances which i don't know to refer to other static fields and that this can't be done in the static constructor. Maybe because the C# compiler cannot prevent you from all careless mistakes. – Tim Schmelter Feb 17 '15 at 09:18
  • @SriramSakthivel: but i see that you have wondered yourself why that is so: http://stackoverflow.com/questions/27725571/why-c-sharp-wont-allow-field-initializer-with-non-static-fields#comment43863499_27725641 – Tim Schmelter Feb 17 '15 at 09:36
  • Yes, I have this question for a while, can't find the answer for the design decision. Maybe I should contact eric or mads directly to get the answer. – Sriram Sakthivel Feb 17 '15 at 09:51
0

Initialization of myconnectionstring variable in your code is incorrect because it depends on another non-static variable. To fix this, just place initialization of myconnectionstring variable into class constructor. See this link for more details about this error.

Alex Kopachov
  • 723
  • 4
  • 9