Home > Blockchain >  I cannot initialize the member variable at the new object
I cannot initialize the member variable at the new object

Time:10-05

Im pretty new to C# and I hope to get some help here. The mypath variable is a placeholder in this case. The class is included by using Programm.src;

This is my code where I want to initialize my input_excel_path variable at the mainWindow1 object.

The outcome in the compiler

error CS0747 : Invalid initializer member declarator and compiler error CS0165: Use of unassigned local variable 'name'.

        MainWindow mainWindow1 = new MainWindow()
        {
            mainWindow1.m_input_excel_path = mypath;
        };

This is my class:

   class MainWindow
   {
    
    public string m_input_excel_path = String.Empty;
    
    public MainWindow(string input_excel_path )
    {
        m_input_excel_path  = input_excel_path;       
    }
}

CodePudding user response:

The object initializer syntax specifies the properties directly, without the variable name. You already have a parametrized constructor, so why not call the constructor directly?

MainWindow mainWindow1 = new MainWindow(mypath);

If you wanted to use the initializer syntax the way you intend, you have to implement a parameterless constructor in your class and then use the correct syntax when initializing:

class MainWindow
{
    
    public string m_input_excel_path = String.Empty;
    
    public MainWindow(string input_excel_path)
    {
        m_input_excel_path = input_excel_path;       
    }

    public MainWindow() {
        // empty ctor required for your initializer to work
    }
}

// somewhere else:
MainWindow mainWindow1 = new MainWindow
{
    m_input_excel_path = mypath
};

The initializer syntax is simply syntactic sugar for the following code:

MainWindow mainWindow1 = new MainWindow();
mainWindow1.m_input_excel_path = mypath;

See What's the difference between an object initializer and a constructor? for more details.

And there's nothing preventing you from mixing a constructor call and initializer syntax. E.g. if you had another field/property in your class:

class MainWindow
{
    
    public string m_input_excel_path = String.Empty;
    public int age;
    
    public MainWindow(string input_excel_path)
    {
        m_input_excel_path = input_excel_path;       
    }
}

// somewhere else:
MainWindow mainWindow1 = new MainWindow(mypath)
{
    age = 42
};
  •  Tags:  
  • c#
  • Related