Strongly-Typed Members When Implementing Interfaces

Problem
You want to know how to provide strongly-typed members when implementing an interface.

Solution
Create weakly-typed members as private members and expose public strongly-typed members with the same name when implementing IEnumerator, ICollection, and IList.

Comments
Current (in the IEnumerator interface), CopyTo (in the ICollection interface), Item, Add, Insert, Remove, Contains, and IndexOf (in the IList interface) are all candidates for this rule. You can reduce the amount of code that developers need to access an interface and make a type more usable by supplying strongly-typed methods.

Example
Here’s an example of how you can provide both weakly and strongly typed versions of the ICollection.CopyTo method.

class AccountCollection : ICollection {
    // An ArrayList that holds Account objects.
    ArrayList accounts = new ArrayList();

    // Private implementation of the CopyTo method.
    void ICollection.CopyTo(Array array, int index) {
        accounts.CopyTo(array, index);
    }

    // Public, strongly-typed version of the CopyTo method.
    public void CopyTo(Account[] array, int index) {
        (this as ICollection).CopyTo(array, index);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s