tags:

views:

68

answers:

3

Say I have a class with 2 properties

class TestClass
{
    public int propertyOne {get;set;}
    public List<int> propertyTwo {get; private set;}
    public TestClass()
    {
        propertyTwo = new List<int>();
    }
}

Using linq, I am trying to create a list of TestClass as follows:

var results = from x in MyOtherClass
              select new TestClass()
              {
                  propertyOne = x.propertyFirst,
                  propertyTwo = x.propertyList
              };

propertyTwo = x.propertyList actually throws an error, with the squiggly red underline.

How can I implement the equivalent of the propertyTwo.AddRange(other) in this case?

Cheers

+2  A: 

As Forgotten Semicolon said above, it seems like the issue here is that your propertyTwo has a private setter.

Try changing your code in TestClass to be :

public List<int> propertyTwo {get; set;}

I don't believe you can initialize properties that are set as private using Asymmetric Accessor Accessibility.

Jamie Dixon
+3  A: 

As others have said you can't set the propertyTwo that way since its declared private. If you just want to set it on construction you could add a second constructor that allows you to pass an initial list, giving you:

class TestClass
{
    public int propertyOne {get;set;}
    public List<int> propertyTwo {get; private set;}

    public TestClass() : this(new List<int>()) { }
    public TestClass(List<int> initialList)
    {
        propertyTwo = initialList;
    }
}
...
var results = from x in MyOtherClass
select new TestClass(x.propertyList)
{
    propertyOne = x.propertyFirst
};
Alconja
+1  A: 

Yes accessibility is the issue here. If you don't want a public setter, you could add a method SetPropertyList() to set the value, effectively doing the same thing in a different way.

Brian