Question

I am trying to pass a value to a list of the same object by using the following code.

Using the following code I get a "A field initializer cannot reference the non-static field, method, or property" error.

If I change the Surname property to fix this I get 2 more errors.

The idea is to create an object of a person and pass their surname on to their children in the list.

The code:

public class Person
{
    public Person()
    {
    }

    private string name = "";
    public string Name
    {
        get { return name; }
        set { if (name != value) name = value; }
    }

    private string surname = "";
    public string Surname
    {
        get { return surname; }
        set { if (surname != value) surname = value; }
    }

    private Children sourceList = new Children(Surname);
    public Children SourceList
    {
        get { return sourceList; }
        set { if (sourceList != value) sourceList = value; }
    }
}

[TypeConverter(typeof(TypeConverter))]
public class Children : List<Person>
{
    public Children(string surname)
    {
        this.ForEach(person => { person.Surname = surname; });
    }
}

Please help? Thanks in advance.

No correct solution

OTHER TIPS

this line is causing you the issue: private Children sourceList = new Children(Surname);

The reason is that field initializers are limited in what they can access, the c# spec states that they can't reference the instance that's being created, so you can' access Surname in a field declaration.

You can set your properties in the constructor

Remove the constructor from Children class, and put the ´foreach statement´ in the set of SourceList, and create a new sourcelist only in the getter if is not inicialized.

Just like this:

  public class Person
    {
        public Person()
        {
        }

        private string name = "";
        public string Name
        {
            get { return name; }
            set { if (name != value) name = value; }
        }

        private string surname = "";
        public string Surname
        {
            get { return surname; }
            set { if (surname != value) surname = value; }
        }

        private Children sourceList;
        public Children SourceList
        {
            get { 
               if(sourceList == null)
                     sourceList = new Children();

               return sourceList; 
           }
            set { if (sourceList != value) 
                 sourceList = value.ForEach(person => { person.Surname = surname; }); 
                }
        }
    }

        [TypeConverter(typeof(TypeConverter))]
        public class Children : List<Person>
        {

        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top