I just started working in a .Net company and I saw this code but I don’t understand what it does. Could somebody shed some light on me ? thanks
/// <summary>
/// If string is string.Empty ("") return null, else returns the copy of the original reference passed in.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string EmptyToNull(this string str)
{
return string.IsNullOrEmpty(str) ? null : str;
}
/// <summary>
/// Converts some native .Net nullable instances of immutable structures to null if they are empty.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Nullable<T> EmptyToNull<T>(this Nullable<T> obj) where T: struct
{
if (obj == null) return null;
else if (obj is Nullable<byte>) return (obj as byte?) == 0 ? null : obj;
else if (obj is Nullable<short>) return (obj as short?) == 0 ? null : obj;
else if (obj is Nullable<int>) return (obj as int?) == 0 ? null : obj;
else if (obj is Nullable<long>) return (obj as long?) == 0 ? null : obj;
else if (obj is Nullable<double>) return (obj as double?) == 0 ? null : obj;
else if (obj is Nullable<float>) return (obj as float?) == 0 ? null : obj;
else if (obj is Nullable<DateTime>) return (obj as DateTime?) == DateTime.MinValue ? null : obj;
else if (obj is Nullable<Guid>) return (obj as Guid?) == Guid.Empty ? (T)default(Nullable<T>) : obj;
else throw new NotImplementedException(string.Format("Method not implemented for type {0}", typeof(Nullable<T>)));
}
/// <summary>
/// Converts some native .Net immutable structures to null if they are empty.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Nullable<T> EmptyToNull<T>(this T obj) where T : struct
{
var val = new Nullable<T>();
val = obj;
if (!val.HasValue) return (T)val;
else if (obj is byte) return (byte)(object)val.Value == 0 ? new Nullable<T>() : obj;
else if (obj is short) return (short)(object)val.Value == 0 ? new Nullable<T>() : obj;
else if (obj is int) return (int)(object)val.Value == 0 ? new Nullable<T>() : obj;
else if (obj is long) return (long)(object)val.Value == 0 ? new Nullable<T>() : obj;
else if (obj is double) return (double)(object)val.Value == 0 ? new Nullable<T>() : obj;
else if (obj is DateTime) return (DateTime)(object)val.Value == DateTime.MinValue ? new Nullable<T>() : obj;
else if (obj is Guid) return (Guid)(object)val.Value == Guid.Empty ? new Nullable<T>() : obj;
else throw new NotImplementedException(string.Format("Method not implemented for type {0}", typeof(T)));
}
First, is it so smart to publish your employer’s code?
Second, apparantly some other part of the code wants empty values (and 0 is threated as empty) to be null values. Value types are used as nullable. That means they can be null, even if they really can’t be, so HasValue is used to find out if a variable is explicitly set.