Domanda

var dlg = new Microsoft.Win32.OpenFileDialog
{
    Title = "Select configuration",
    DefaultExt = ".xml",
    Filter = "XML-file (.xml)|*.xml",
    CheckFileExists = true
};

I got the above piece of got from this post. Is the part inside the curly braces assigning values via Accessors. There appears to be no constructors, so does it imply the default one is called and then Property values assigned.

È stato utile?

Soluzione

What you've shown is called an object initializer, a syntactical feature introduced in C# 3.0.

It is similar to the following code, which creates an object in the first line, and then sets its properties individually in the subsequent lines:

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;

However, it is not identical to the above code. When you use an object initializer, the compiler will create a temporary variable, set the properties on the object contained in that temporary variable, and then assign that temporary variable to the real variable that you declared. The net result is that the creation of the object instance is atomic. More detailed information is available in the answers to this question, and in this blog post.

In practice, you can imagine the resulting code looking something like this when fully expanded:

var temporaryDlg = new Microsoft.Win32.OpenFileDialog();
temporaryDlg.Title = "Select configuration";
temporaryDlg.DefaultExt = ".xml";
temporaryDlg.Filter = "XML-file (.xml)|*.xml";
temporaryDlg.CheckFileExists = true;

var dlg = temporaryDlg;

As for your question about which constructor is called, yes, it is the default constructor in both cases. The first line is a call to the constructor, when it says new. You can tell it's the default constructor because no parameters are passed in.

Altri suggerimenti

Yes it is identical to:

var dlg = new Microsoft.Win32.OpenFileDialog();

dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;

It does exactly what you guessed - call the constructor, then use the public property settors.

Yes, it implies the same i-e created with default constructor and used accessors to assign the value, its the .net3.5 or above syntax to support object initialization

Yes, this is syntactic sugar. The compiler will generate the following code for this:

var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top