0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# で Between

Last updated at Posted at 2021-08-17

はじめに

ネットを探すとすぐに見つかるのですが、念のため自分用のスニペットを。

追記

From ... To がそれぞれ「含む」「含まない」が指定できないため、指定できるものをつくりました。

C# で Between(やりすぎバージョン) - Qiita

サンプルコード

using System;

namespace BetweenTest
{
    static class Ext
    {
        public static bool Between<T>(this T source, T low, T high) where T : IComparable
        {
            if (low.CompareTo(high) > 0) { throw new ArgumentException(); }
            return source.CompareTo(low) >= 0 && source.CompareTo(high) <= 0;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            if (5.Between(0, 9))
            {
                Console.WriteLine("Hello World!");
            }

            if ("5".Between("0", "9"))
            {
                Console.WriteLine("Hello World!");
            }
        }
    }
}

使い所

VB では問題なくできるのですが、C# では以下のように書くとエラーになります。

if ("0" <= val && val <= "9")
{
    // ...
}

文字列の比較に <= とか書けないのです1。こんな時に Between があると次のように書けるので助かります。

if (val.Between("0", "9"))
{
    // ...
}
  1. しかもこの時の業務は val に英字記号も入ってきていたので int.Parse も許されなかったのです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?