Why the C# property initializer (new()) is written as that?

    Info myPath = new Info()
    {
        path = oFile.FileName
    };
    ...
    class Info
    {
        public string path;
        public string Path
        {
            get { return path; }
            set { path = value; }
        }
    }

Above is the C# code from some program and it can work normally. But I don't understand it well. The first question is that why path = oFile.FileName is not written as path = oFile.FileName; ? Why the semicolon can be removed?

The second question is that why I cannot write it like this: myPath.path = oFile.FileName ? There will give error message by Visual Studio 2012.

Could anyone please help? Thanks!

Jon Skeet
people
quotationmark

That construct is an object initializer. It's not a list of arbitrary statements - it's only initialization of fields and properties, and they're comma-separated:

Foo x = new Foo // Implicitly calls the parameterless constructor
{
    Property1 = value1,
    Property2 = value2
};

That's shorthand for:

Foo tmp = new Foo();
tmp.Property1 = value1;
tmp.Property2 = value2;
Foo x = tmp;

Object initializers were introduced in C# 3, along with collection initializers which are effectively syntactic sugar for repeated calls to Add. So:

List<string> names = new List<string>
{
    "Foo", "Bar"
};

is equivalent to:

List<string> tmp = new List<string>();
tmp.Add("Foo");
tmp.Add("Bar");
List<string> names = tmp;

people

See more on this question at Stackoverflow