# Wednesday, October 28, 2009
« Tip of the Day: Winform: Displaying the ... | Main | Tip of the day: Opening a process and (o... »

This routine checks the specified minimum and maximum string lengths, and either returns True/False that it meets those requirements, or could also throw an exception (based on the throwException parameter value).

This would also be a good candidate for an extension method. To do so, add a parameter (in the first position) as “this string”.

        /// <summary>

        /// Checks the length of a string to see if it meets the minimum and maximum length

        /// </summary>

        /// <param name="checkString">string to check</param>

        /// <param name="minLength">minimum string length</param>

        /// <param name="maxLength">maximum string length</param>

        /// <param name="stringName">description of the value to check</param>

        /// <param name="throwException">T/F to throw an exception if it exceeds the maximum</param>

        /// <returns>T/F</returns>

        public static bool ValidString(string checkString, int minLength, int maxLength, string stringName, bool throwException)

        {

            if ((checkString.Length >= minLength) && (checkString.Length <= maxLength))

                return true;

            else

            {

                if (checkString.Length < minLength)

                    if (throwException)

                        throw new System.ArgumentOutOfRangeException("The argument string - " + stringName + " was less than the minimum length.");

                    else

                        return false;

                if (checkString.Length > maxLength)

                    if (throwException)

                        throw new System.ArgumentOutOfRangeException("The length (" + checkString.Length.ToString() + ") of argument string - " + stringName + " was longer than the expected length(" + maxLength.ToString() + ").");

                    else

                        return false;

                return false;

            }

 

        }

 

Comments are closed.