W
Wiktor Zychla [C# MVP]
Following code was supposed to sort an ArrayList of strings while keeping
one "fixed" element at the last position.
However, the code hangs in .NET 1.1. I think that answering these questions
should be an interesting and instructive task for .NET learners:
1. why the code hangs in .NET 1.1?
2. why it does not hang in .NET 2.0?
3. why it does not hang in .NET 1.1 when you keep the "fixed" element at the
first (instead of last) position:
if ( ys == "fixed" )
return 1;
if ( xs == "fixed" )
return -1;
4. how to fix the code of the comparer so that sorting works in .NET 1.1?
Regards,
Wiktor Zychla
using System;
using System.Collections;
class TestComparer : IComparer
{
public int Compare(object x, object y)
{
if (!( x is string )) return 0;
if (!( y is string )) return 0;
string xs = x as string;
string ys = y as string;
if ( ys == "fixed" )
return -1;
if ( xs == "fixed" )
return 1;
return xs.CompareTo( ys );
}
}
class Test
{
public static void Main()
{
ArrayList test = new ArrayList();
test.Add( "test2" );
test.Add( "test1" );
test.Add( "fixed" );
test.Add( "test5" );
test.Add( "test4" );
test.Add( "test3" );
foreach ( string s in test )
Console.WriteLine( s );
Console.WriteLine();
test.Sort( new TestComparer() );
foreach ( string s in test )
Console.WriteLine( s );
}
}
one "fixed" element at the last position.
However, the code hangs in .NET 1.1. I think that answering these questions
should be an interesting and instructive task for .NET learners:
1. why the code hangs in .NET 1.1?
2. why it does not hang in .NET 2.0?
3. why it does not hang in .NET 1.1 when you keep the "fixed" element at the
first (instead of last) position:
if ( ys == "fixed" )
return 1;
if ( xs == "fixed" )
return -1;
4. how to fix the code of the comparer so that sorting works in .NET 1.1?
Regards,
Wiktor Zychla
using System;
using System.Collections;
class TestComparer : IComparer
{
public int Compare(object x, object y)
{
if (!( x is string )) return 0;
if (!( y is string )) return 0;
string xs = x as string;
string ys = y as string;
if ( ys == "fixed" )
return -1;
if ( xs == "fixed" )
return 1;
return xs.CompareTo( ys );
}
}
class Test
{
public static void Main()
{
ArrayList test = new ArrayList();
test.Add( "test2" );
test.Add( "test1" );
test.Add( "fixed" );
test.Add( "test5" );
test.Add( "test4" );
test.Add( "test3" );
foreach ( string s in test )
Console.WriteLine( s );
Console.WriteLine();
test.Sort( new TestComparer() );
foreach ( string s in test )
Console.WriteLine( s );
}
}