嗚嗚喔學習筆記: C# Array or List Safe

搜尋此網誌

2022年4月7日 星期四

C# Array or List Safe

Array & List 常常要做 null check & out of range check 寫起來麻煩 把這段寫成擴充函式方便些


public static class ArraySafe

{

    public static bool IsSafe<T>(this T[] array, int index)

    {

        return array != null && index >= 0 && index < array.Length;

    }


    public static bool IsSafe<T>(this System.Collections.Generic.List<T> array, int index)

    {

        return array != null && index >= 0 && index < array.Count;

    }


    public static bool TryGetElement<T>(this T[] array, int index, out T element)

    {

        if (array == null || index < 0 || index >= array.Length)

        {

            element = default(T);

            return false;

        }


        element = array[index];

        return true;

    }


    public static bool TryGetElement<T>(this System.Collections.Generic.List<T> list, int index, out T element)

    {

        if (list == null || index < 0 || index >= list.Count)

        {

            element = default(T);

            return false;

        }


        element = list[index];

        return true;

    }

}


沒有留言:

張貼留言