Check if the string is null or empty, if yes, return the replace string instead. - CSharp System

CSharp examples for System:String Replace

Description

Check if the string is null or empty, if yes, return the replace string instead.

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;//  w  ww.j  a v a  2  s .  c o  m

public class Main{
        /// <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