initializing properties with private sets in .Net

Posted by Martin Neal on Stack Overflow See other posts from Stack Overflow or by Martin Neal
Published on 2010-05-07T01:07:30Z Indexed on 2010/05/07 1:18 UTC
Read the original article Hit count: 209

Filed under:
|
|
public class Foo
{
    public string Name { get; private set;} // <-- Because set is private,
}

void Main()
{
    var bar = new Foo {Name = "baz"}; // <-- This doesn't compile
    /*The property or indexer 'UserQuery.Foo.Name' cannot be used 
      in this context because the set accessor is inaccessible*/

    using (DataContext dc = new DataContext(Connection))
    {
        // yet the following line works.  **How**?
        IEnumerable<Foo> qux = dc.ExecuteQuery<Foo>(
           "SELECT Name FROM Customer");
    }
    foreach (q in qux) Console.WriteLine(q);
}

I have just been using the private modifier because it works and kept me from being stupid with my code, but now that I need to create a new Foo, I've just removed the private modifier from my property. I'm just really curious, why does the ExecuteQuery into an IEnumerable of Foo's work?

© Stack Overflow or respective owner

Related posts about c#

Related posts about private