C# Puzzlers: The Joy of Lists

My quest to take a “deep dive” into C# has led me to this variation on the ShortSet Java Puzzler. I translated the ShortSet class, described in Java Puzzlers, to C#. C# does not have a Set class, so I used List.

public class ShortList{    public static void Main(string[] args)    {        IList<short> l = new List<short>();        for(short i=0; i<100; i++)        {            l.Add(i);            l.Remove(i - 1);        }        Console.WriteLine(l.Count);        Console.Write("Press any key to continue . . . ");        Console.ReadKey(true);    }}

What gets printed to the console?Well… this code does not even compile. List defines the Remove method as Remove(T value). The compiler correctly tells us that i - 1 is an int. We cannot remove an int from a List<short>.The Java compiler correctly allows this to compile, because Set’s remove method is defined with Object as a parameter. Remove is defined this way for backward compatibility.Does C# always behave as expected?My second attempt at a “deep dive” results in another boring/pointless example. Does C# not have puzzler material? Is it really that well designed?Where are the C# edge cases?


One Response

  1. […] finde ich auch den Ansatz von Adam Esterline nach C# Puzzlers (1, 2) ähnlich zu den Java Puzzlers zu suchen. Allerdings glaube ich nicht, dass die direkte […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: