lawwz

Hi I am having trouble with one or two lines of code below.

These lines are commented...... hope you wont mind helping ,

thanks...

using System;

using system.collections;

using System.Collections.Generic;

using System.Text;

namespace ch11ex05

{

class PersonCompareName : IComparer

{

//what is this line doing..

// I know IComparer expose the single method Compare,

/// which return integer.... but not sure what the line below is doing

//

public static IComparer Default = new PersonCompareName();

public int Compare(object x, object y)

{

if (x is person && y is person)

{

return Comparer.Default.Compare(((person)x).Name, ((person)y).Name);

}

else

{

throw new ArgumentException("one or both objects to compare are not person objects. ");

}

}

}

}



Re: .NET Base Class Library IComparer

TaylorMichaelL

The line is a field declaration for the field Default (bad name) of type IComparer. It is initialized to an instance of the PersonCompareName class. This particular field allows clients to use this custom comparer without having to instantiate it. In code, whereever a comparer is needed, you can write

PersonCompareName.Default

Rather than

new PersonCompareName()

StringComparer does the same thing by exposing a few standard comparers as static fields.

Michael Taylor - 5/30/07

http://p3net.mvps.org





Re: .NET Base Class Library IComparer

lawwz

So this line

public static IComparer Default = new PersonCompareName();

is like a handle to the new PersonComparName()..

In the book i am reading it says "The .Net Framework includes a default implementation for the ICompare interface on a class called Comparer.

It has a line of code :

Comparer.Defualt.Compare(firststring , secondstring).

What is this Defualt..... its not built in

The line in code public static defines the variable Default.. so I thought it was kind of part of the language....

so from what i understand we can replace Default by any name that we wish

such as

public static IComparer Default = new PersonCompareName();

public static IComparer myhandle = Default;