c# リファクタリング 小さい方の値が欲しい。
二つのint型から小さい方の値がほしい時。
public void Hoge(int one,int other) { int min; if (one < other) { min = one; } else { min = other; } }
じゃなくて。MathクラスのMinメソッドを使おう。
public void Hoge(int one,int other) { int min; min = Math.Min(one, other); }
MSDNで見ればわかることですが、longやbyte等、大体の型のオーバーロードが用意されています。
大きい方の値であればMath.Max
https://msdn.microsoft.com/ja-jp/library/system.math.max(v=vs.110).aspx
DateTime構造体にもこういうのないものかなぁと思ったらStackOverFlowでも似たような話がありました。
残念な英語力なので雰囲気で提案されている解決方法を真似してみます。
まずは三項演算子
DateTime min; min = one < other ? one : other;
Ticksプロパティ(long型)をMathクラスに渡す方法
DateTime min;
min = new DateTime(Math.Min(one.Ticks, other.Ticks));
Utilityクラス見たいなので再利用する。
public static class DateTimeUtil { public static DateTime Min(DateTime one,DateTime other) { return new DateTime(Math.Min(one.Ticks, other.Ticks)); } public static DateTime Max(DateTime one, DateTime other) { return new DateTime(Math.Max(one.Ticks, other.Ticks)); } }
最後に挙げた安易にユーティリティクラスを作ることの是非は別として、
TicksをMathクラスに渡すのはへぇ~ってなりました。