Transition to generics.

I am moving winforms application 1.1 to 2.0. What are the main things that I have to change immediately due to generics. Here is what I still have:

  • Replace all hash tables with shared dictionaries
  • Replace all arraylists with List <>
  • Replace all collectionBase collection classes: List <>

Any other things to do immediately?

Thks, ak

+6
generics c # winforms
source share
6 answers

Any other things to do immediately?

Generally, change any mention of IEnumerable to IEnumerable<T> where possible. Migration can be greatly facilitated by switching the entire namespace, i.e. Un- import ing System.Collections in each file and instead of importing System.Collections.Generic .

Also, find mentions of object and / or use of boxing in your code and consider whether this is appropriate or whether to be replaced with generics.

As jalf reminded me in the comments, another important change is the switch to the generic version of IComparable , where applicable.

+7
source share

I do not think that everything should be done immediately! Code 1.1 works, right? What is a business case for wholesale swap to generics? Compile the application under 2.0, run it and test it. And then, when you need new functions that allow you to make good use of generics, implement these functions as universal.

+8
source share

General collections are certainly preferable because of their expressiveness. One thing to keep in mind when moving from non-generic collections is that sometimes the behavior may be different than expected. For example, using an indexer in a Hashtable and a Dictionary will act differently for values ​​that aren't there. Hashtable will return null while the Dictionary returns.

 Hashtable ht = new Hashtable(); ht.Add(1, "one"); string s1 = ht[1; // s1="one" string s2 = ht[2]; // s2=null var dic = new Dictionary<int, string>(); dic.Add(1, "one"); string s1 = dic[1]; // s1="one" string s2 = dic[2]; // throws KeyNotFoundException 

A common way to handle this is to use the following technique:

 string s = null; if (dic.TryGetValue(k, out s)) { // if we're here, k was found in the dictionary } 

This will only be displayed at runtime, so it’s worth knowing in advance.

+3
source share

See Bill Wagner's new book More Effective C # . There are many great tips for moving on to generics.

+2
source share

I would not recommend using List<T> instead of CollectionBase . Instead, Collection<T> gives comparable overrides.

0
source share

if you don’t already have a unit test suite with excellent code coverage, do not change anything unnecessarily

otherwise, you just ask for trouble, not to mention inventing work ...

0
source share

All Articles