0

This illustrates what I am trying to accomplish:

public class GridModel : PropertyChangedBase
{
    public List<string> LeftValue { get; set; }
    public List<string> LeftValue = new List<string> { "Alpha", "Beta", "Gamma" };
    [...]
}

but I am getting an obvious "identifier repeated" error.

Is there a syntax for that? Perhaps with a constant or fixed List?

Travis Banger
  • 697
  • 1
  • 7
  • 19

3 Answers3

3

You can't initialize a property's backing field when you declare a property.

You'll have to do it in the constructor or simply not use an auto-implemented property, and initialize the backing field directly.

public class GridModel : PropertyChangedBase
{
    private List<string> _leftValue = new List<string> { "Alpha", "Beta", "Gamma" };
    public List<string> LeftValue
    {
        get { return _leftValue; }
        set { _leftvValue = value; }
    }    
}
dcastro
  • 66,540
  • 21
  • 145
  • 155
  • You cannot set `_leftvValue` in a setter when declared `readonly`. Either remove the setter or the identifier. – Silvermind Dec 01 '13 at 01:02
  • Sorry, but shouldn't it also be `new List (new [] { "Alpha", "Beta", "Gamma" });` or `(new [] { "Alpha", "Beta", "Gamma" }).ToList();` – Silvermind Dec 01 '13 at 01:09
  • 1
    No, these are called collection initializers. The compiler will create an "Add" call for each item inside brackets: http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx – dcastro Dec 01 '13 at 01:13
3

You can initialize it using backing field:

public class GridModel : PropertyChangedBase
{
    private List<string> leftValue = new List<string> { "Alpha", "Beta", "Gamma" };

    public List<string> LeftValue 
    { 
        get
        {
            return leftValue;
        }
        set
        {
            leftValue = value;
        } 
    }

    [...]
}
Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
2

There are some examples at Using Properties (C# Programming Guide), e.g.

private int month = 7;  // Backing store 

public int Month
{
    get
    {
        return month;
    }
}
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198