Exercise: Generic methods

The class System.Math contains a lot of mathematical utility (static) methods. Some of these methods are heavily overloaded like the Min(a, b).

In this exercise you will make generic versions of some of these methods.

Geting started

Create a new Solution in Visual Studio. Name the new Solution "GenericMethods".

Create a class named MathGeneric. This class should NOT be generic - but it will contain generic methods.

Make the class static to avoid programmers from making object.

	public static class MathGeneric { ... }

Generic Min(...) and Max(...) using IComparable

In class MathGeneric add 2 static generic methods

Test the methods with a unit test. Make sure you try different types like int, String and a homemade type like Student.

Implementing IComparable

class Student : IComparable<Student> {
  int id;
  String name;
....
int CompareTo(Student other) { return this.id - other.id; } 
    // if this.id > other.id then the return value will be positive,

int CompareTo(Student other) { return this.name.CompareTo(other.name); } 
    // comparing two studens is not reduced to comparing two Strings (the names)
}

You can only make ONE of the CompareTo methods in the Student class

Generic Min(...) and Max(...) using IComparer

Test the methods with a unit test. Make sure you try different types like int, String and a homemade type like Student.

You will probably have to create some classes implementing IComparer<int>, etc.

IComparer

Class StudentNameComparer<Student> {
  public bool Compare(Student st1, Student st2) { return st1.name.CompareTo(st2.name); 
}

Very similar to IComparable. IComparable should be implemented by a model class whereas IComparer should be implemented by a separate class.

With IComparer you should not refer to this, since this is the IComparer object.

Generic frequency collection

Sometimes when you analyze a text you want to know how many times every word occurs in the text.

This could information can be collected using a method like

      public static IDictionary<String, int> Frequencies(Collection<String> words)

The resulting dictionary contains an entry for each word in the text: (key, value) = (word, number of times the word occurs in the text)

 

I want to take this a step further, so that it works on all kinds of types, not only String's.

Make a method like

      public static IDictionary<T, int> Frequencies<T>(ICollection<T> elements) { ... }
Testing? Yes!

Extra: Intersection

Make a method like

      public static ICollection Intersection<T>(ICollection<T> coll1, ICollection<T> coll2) { ... }

The method should return the intersection of the two collections, i.e. the elements which are present in both colletions.

You must decide how to deal with duplicate elements in the parameter lists.

Testin: As always.