ILearnable .Net

May 20, 2009

params T[] vs IEnumerable<T>

Filed under: Uncategorized — andreakn @ 07:34

Just got bitten by a fascinating little gem.

I have extracted the essentials in the code below. What do you think the output is?

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            Console.WriteLine(p.DoStuff(5, 6, 7));
        }

        public string DoStuff(IEnumerable<int> ints)
        {
            Console.WriteLine("ienum");
            return "avg = "+ints.Average();
        }
        public string DoStuff(params int[] ints)
        {
            Console.WriteLine("params");
            return DoStuff(ints);
        }
    }

It prints “params” like its nobodys business before it crashes on a stackoverflow

The intent was of course to provide two methods with slightly different signatures that does the same, one calling the other under the hood. so if you have many ints you stuff them into a list, but if you have few you can call DoStuff with the ints directly. (no, my code didn’t calculate averages of ints, the ints are just for illustration)

Turns out that given an array of type T, the params method gets precedense. If you cast to an IEnumerable of type T, the other one gets preference

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

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

Blog at WordPress.com.

%d bloggers like this: