views:

69

answers:

2

Hi,

I am reading through Jon Skeet's "C# in Depth", first edition (which is a great book). I'm in section 3.3.3, page 84, "Implementing Generics". Generics always confuse me, so I wrote some code to exercise the sample. The code provided is:

using System; 
using System.Collections.Generic;

public sealed class Pair<TFirst, TSecond> : IEquatable<Pair<TFirst, TSecond>>
{
    private readonly TFirst first; 
    private readonly TSecond second;

    public Pair(TFirst first, TSecond second) 
    {
        this.first = first; 
        this.second = second;
    }


    ...property getters...


    public bool Equals(Pair<TFirst, TSecond> other) 
    {
        if (other == null) 
        {
            return false;
        } 
        return EqualityComparer<TFirst>.Default.Equals(this.First, other.First) &&    
            EqualityComparer<TSecond>.Default.Equals(this.Second, other.Second);
    }

My code is:

class MyClass
{
    public static void Main (string[] args)
{
    // Create new pair.
    Pair thePair = new Pair(new String("1"), new String("1"));

    // Compare a new pair to previous pair by generating a second pair.
    if (thePair.Equals(new Pair(new string("1"), new string("1"))))
        System.Console.WriteLine("Equal");
    else
        System.Console.WriteLine("Not equal");
    }
}

The compiler complains:

"Using the generic type 'ManningListing36.Paie' requires 2 type argument(s) CS0305"

What am I doing wrong ?

Thanks,

Scott

+2  A: 
    Pair<string, string> thePair = new Pair<string, string>("1", "1");

    // Compare a new pair to previous pair by generating a second pair.
    if (thePair.Equals(new Pair<string, string>("1", "1")))
        System.Console.WriteLine("Equal");
    else
        System.Console.WriteLine("Not equal");

The type Pair as you use it is Pair<T1, t2>
Preet Sangha
Hmm. Still doesn't work. Complains about the new String paramenters in the Pair constructor (i.e. Pair<string, string>(new string("1"), ..
Scott Davies
try Pair<string, string> thePair = new Pair<string, string>("1", "2") does this work?
Preet Sangha
Thought of that and just tried it - it works! The String() constructor expected char as opposed to a string, so "1" works. Thanks!
Scott Davies
+2  A: 

You have to specify what types you are using.

Pair<String, String> thePair = new Pair<String, String>(new String("1"), new String("1"));
Corey Sunwold