Members that contain executable code are collectively known as the function members of a class. The preceding section describes methods, which are the primary kind of function members. This section describes the other kinds of function members supported by C#: constructors, properties, indexers, events, operators, and destructors.
The following table shows a generic class called List<T>, which implements a growable list of objects. The class contains several examples of the most common kinds of function members.
public class List<T> {
|
const int defaultCapacity = 4;
| Constant
|
T[] items; int count;
| Fields
|
public List(int capacity = defaultCapacity) { items = new T[capacity]; }
| Constructors
|
public int Count { get { return count; } }
public int Capacity { get { return items.Length; } set { if (value < count) value = count; if (value!= items.Length) { T[] newItems = new T[value]; Array.Copy(items, 0, newItems, 0, count); items = newItems; } } }
| Properties
|
public T this[int index] { get { return items[index]; } set { items[index] = value; OnChanged(); } }
| Indexer
|
public void Add(T item) { if (count == Capacity) Capacity = count * 2; items[count] = item; count++; OnChanged(); }
protected virtual void OnChanged() { if (Changed!= null) Changed(this, EventArgs.Empty); }
public override bool Equals(object other) { return Equals(this, other as List<T>); }
static bool Equals(List<T> a, List<T> b) { if (a == null) return b == null; if (b == null || a.count!= b.count) return false; for (int i = 0; i < a.count; i++) { if (!object.Equals(a.items[i], b.items[i])) { return false; } } return true; }
| Methods
|
public event EventHandler Changed;
| Event
|
public static bool operator ==(List<T> a, List<T> b) { return Equals(a, b); }
public static bool operator!=(List<T> a, List<T> b) { return!Equals(a, b); }
| Operators
|
}
|