Fork me on GitHub


[C#] the error "Object reference not set to an instance of an object"

會發生這個 error 的原因是: The code is trying to access a member of a reference type variable that is set to null.

當使用automatic properties 的時候,如果沒有初始化 value type 的 property 會是 0, reference type 則會是 null。因此在建構子當中要針對 properties 做初始化的動作 ( "new" )




[C# 筆記] Collections and Generics 集合和泛型

  • Collections 解決 System.Array 只能裝載同一型別之物件和固定長度的容量之限制。Generics 提供更高的 type safety 和 performance。

  • System.Collections 這個 namespace 實現了許多 interfaces 像是: ICollection, IComparer, IDictionary, IDictionaryEnumerator, IEnumerable, IEnumerator, IHashCodeProvider, IList

  • The Role of ICollection

    • ICollection 是最主要的 interface,他允許你 (a) 取得 container 內物件的數量 (b) the thread safety of the container (c) the ability to copy the contents into a System.Array type

    • public interface ICollection : IEnumerable
      int Count { get; }
      bool IsSynchronized { get; }
      object SyncRoot { get; }
      void CopyTo(Array array, int index);

  • The Role of IDictionary
    • A dictionary is simply a collection that maintains a set of name/value pairs

    • public interface IDictionary : ICollection, IEnumerable
        bool IsFixedSize { get; }
        bool IsReadOnly { get; }
        // Type indexer; see Chapter 12 for full details.
        object this[object key] { get; set; }
        ICollection Keys { get; }
        ICollection Values { get; }
        void Add(object key, object value);
        void Clear();
        bool Contains(object key);
        IDictionaryEnumerator GetEnumerator();
        void Remove(object key);

  • The Role of IDictionaryEnumerator

    • IDictionaryEnumerator is simply a strongly typed enumerator, given that it extends IEnumerator by adding the following functionality:

      public interface IDictionaryEnumerator : IEnumerator
        DictionaryEntry Entry { get; }
        object Key { get; }
        object Value { get; }

  • The Role of IList

    • provides the ability to insert, remove, and index items into (or out of) a container

    • public interface IList : ICollection, IEnumerable
        bool IsFixedSize { get; }
        bool IsReadOnly { get; }
        object this[ int index ] { get; set; }
        int Add(object value);
        void Clear();
        bool Contains(object value);
        int IndexOf(object value);
        void Insert(int index, object value);
        void Remove(object value);
        void RemoveAt(int index);

  • The Class Types of System.Collections