LoginSignup
3
2

More than 5 years have passed since last update.

小ネタ:Index付きSelectが限界超えたらどー成るか?

Last updated at Posted at 2016-11-02

どーいうことだってばよ?

public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source,Func<TSource, int, TResult> selector)sourceの要素数が、Int32.MaxValue超えたらどーなるのか気になったので試してみた。

試してみたこと

以下のようなモノをこさえて、後はひたすら回すべしw


using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
    class Program
    {
        static IEnumerable<long> CreateSequence()
        {
            for (long i = 0; i <= 2147483648; i++) yield return i;
        }
        static void Main(string[] args)
        {
            try
            {
                foreach (var elem in CreateSequence().Select((l, i) => new KeyValuePair<int, long>(i, l)))
                {
                    if (elem.Value%1000000 == 0)
                    {
                        Console.WriteLine((elem.Value/2147483648.0*100).ToString("F2") + "%");
                    }
                }
            }
            catch (OverflowException)
            {
                Console.WriteLine("Overflow detected!");
            }

            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }

    }
}

こいつを、/checked-でコンパイルしてOverFlowExceptionが飛んでくるかどうか試してみた。

結果とまとめ

飛んできた。
当該部分のコードリーディングしたところ、インデックスとして、selectorデリゲートに渡される変数のインクリメント部分が、明示的にcheckedブロックで括られていたのでまぁそりゃそうなるよね。
Int32.MaxValue超えるなんてそうそう無いとは思うけど、これも後学の為ということで一つ。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2