convert string to a long value if possible. - CSharp System

CSharp examples for System:String Convert

Description

convert string to a long value if possible.

Demo Code


using System.Xml;
using System.Web;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from  w w  w . j  ava2  s .co m

public class Main{
        /// <summary>
        /// convert string to a long value if possible.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theDefault">the replace value if string could not convert to long</param>
        /// <returns>a Int64 value</returns>
        public static long ToLong(this string theSource, long theDefault)
        {
            long tempValue;
            return long.TryParse(theSource.TrimNull(), out tempValue) ? tempValue : theDefault;
        }
        /// <summary>
        /// convert string to a long value if possible, if failed, return 0 as default value.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a Int64 value</returns>
        public static long ToLong(this string theSource)
        {
            return theSource.ToLong(0);
        }
        /// <summary>
        /// Check if the string is null or empty, if yes, return the replace string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="replacer">the replace function</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource, Func<string> replacer)
        {
            return string.IsNullOrEmpty(theSource) ? replacer() : theSource;
        }
        /// <summary>
        /// Check if the string is null or empty, if yes, return the replace string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <param name="theReplace">the replace string</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource, string theReplace)
        {
            return string.IsNullOrEmpty(theSource) ? theReplace : theSource;
        }
        /// <summary>
        /// Check if the string is null, if yes, return an empty string instead.
        /// </summary>
        /// <param name="theSource">the souce string</param>
        /// <returns>a string</returns>
        public static string TrimNull(this string theSource)
        {
            return theSource ?? string.Empty;
        }
}

Related Tutorials