2014年6月1日日曜日

TryParseでTryブロック追放 - C#ショートプログラミング -

OLD
class Program
    {
        static void Main(string[] args)
        {
            string src = "123";
            try
            {
                System.Diagnostics.Debug.WriteLine(int.Parse(src));
            }
            catch (Exception)
            {
                System.Diagnostics.Debug.WriteLine(-1);
            }
        }
    }

NEW
class Program
    {
        static void Main(string[] args)
        {
            string src = "123";
            int result;
            System.Diagnostics.Debug.WriteLine(int.TryParse(src, out result) ? result : -1);
        }
    }

Result

123

・例外処理は重い処理なので、できるだけ利用は避けるのが定石


引用元:
C#ショートプログラミング





0 件のコメント:

コメントを投稿