using System; namespace EasyDevCore.Common { /// /// /// public static class NullHelper { /// /// Default value of DBNull /// /// /// internal static object DefaultValue(Type type) { if (type.Equals(typeof(byte)) || type.Equals(typeof(Int16)) || type.Equals(typeof(int)) || type.Equals(typeof(Int64)) || type.Equals(typeof(ushort)) || type.Equals(typeof(uint)) || type.Equals(typeof(UInt16)) || type.Equals(typeof(UInt32)) || type.Equals(typeof(UInt64))) { return (byte)0; } else if (type.Equals(typeof(Single))) { return (Single)0; } else if (type.Equals(typeof(double))) { return (double)0; } else if (type.Equals(typeof(decimal))) { return (decimal)0; } else if (type.Equals(typeof(DateTime))) { return DateTime.MinValue; } else if (type.Equals(typeof(string))) { return string.Empty; } else if (type.Equals(typeof(bool))) { return false; } else if (type.Equals(typeof(Guid))) { return Guid.Empty; } else if(type.IsNullable()) { return null; } else { throw new NotSupportedException("Type is not supported"); } } /// /// Replaces NULL with the specified replacement value. /// /// Is the expression to be checked for NULL /// Is the expression to be returned if check_value is NULL. replacement_value must have the same type as check_value. /// The value of check_value is returned if it is not NULL; otherwise, replacement_value is returned public static T IsNull(T checkValue, T replaceValue) { if (checkValue == null || Convert.IsDBNull(checkValue)) { return (T)replaceValue; } return checkValue; } /// /// Return first value is not null /// /// values /// public static T Coalesce(params T[] args) { foreach (T value in args) { if (value != null && !Convert.IsDBNull(value)) { return value; } } return default; } /// /// Convert Null value to default value /// /// /// public static T NullToDefault(T value) { #pragma warning disable CS8604 // Possible null reference argument. return (T)IsNull(value, DefaultValue(typeof(T))); #pragma warning restore CS8604 // Possible null reference argument. } /// /// Values if null or empty. /// /// /// The input. /// The default if null or empty. /// public static T ValueIfNullOrEmpty(this T input, T defaultIfNullOrEmpty) { if (input is string) { return string.IsNullOrWhiteSpace(input.ToString()) ? defaultIfNullOrEmpty : input; } else { return (input is null ? defaultIfNullOrEmpty : input); } } /// /// Nulls if value equals checkvalue. /// /// /// The value. /// The check value. /// null if equals else return value public static T NullIf(T value, T checkValue) { if (value is null || checkValue is null || object.Equals(value, checkValue)) { return default(T); } return value; } } }