Hello, please explain why an error occurs:

A field initializer cannot refer to the non-static field, method, or property GenericsHW.MyList.array.


Indeed, in the Contains(T item) method, exactly the same cycle is organized, but there is no error; what is it connected with? Moreover, if I make the array static, then everything is OK (why do I need to write static?). Thank you in advance :)


 namespace GenericsHW { interface IMyList<T> { void Add(T a); T this[int index] { get; } int Count { get; } void Clear(); bool Contains(T item); } class MyList<T>:IMyList<T> { T[] array = null; delegate void ShowArrayElements(); public MyList() { array = new T[0]; } public int Count { get { return array.Length; } } public void Add(T a) { T[] temp = new T[array.Length + 1]; for (int i = 0; i < array.Length; i++) temp[i] = array[i]; temp[array.Length] = a; array = temp; } public T this[int index] { get { return array[index]; } } public void Clear() { array = new T[0]; } public bool Contains(T item) { foreach (T ar in array) { if (ar.Equals(item)) return true; } return false; } public override string ToString() { return String.Format("Количество элементов массива:{0}\n", array.Length); } private ShowArrayElements ShowArray = () => { foreach (T ar in array) { Console.WriteLine("{0} ",ar); } }; } } 
  • and what is not clear in the error itself? A field initializer cannot be used to reference the non-static field, method, or propertynon-static fields, methods and properties cannot be used during field initialization - Grundy
  • 2
    transfer the initialization to the constructor and it will work - Grundy
  • @Grundy: Why not as an answer? - VladD
  • @VladD, oh, I just wanted to call you here :-) I wonder why the inside of the delegate being assigned should also not use non-static fields, because it is only assigned and not executed :) - Grundy
  • @VladD, well, that’s why we need to somehow explain :-) and one line is somehow not that :) well, and I remember exactly how it was about field initialization - Grundy

1 answer 1

Mistake

A field initializer cannot be used to reference the non-static field, method, or property


When initializing fields, non-static fields, methods and properties cannot be used.

It clearly says that you cannot use non-static class members when using an initializer, that is, when a value is assigned to a field directly in the body of the class when declared, and not in the constructor.

To get around this problem, you can transfer the initialization of this delegate to the constructor, for example:

 private ShowArrayElements ShowArray; public MyList() { array = new T[0]; ShowArray = () => { foreach (T ar in array) { Console.WriteLine("{0} ",ar); } }; } 

Links to Eric Lippert’s article explaining this behavior:

  1. First part
  2. The second part of