ExtensionMethod.NET Home of 817 C#, Visual Basic, F# and Javascript extension methods

ToString(NullOptions)

This ToString() version is null aware. That means it has different behaviors if the object's value is null or DBNull according to the NullOptions enum.

Source

public enum NullOptions
{
    ConvertDbNullsToNulls,
    ConvertAllNullsToEmpty
}
  
public static string ToString(this object obj, NullOptions nullOption)
{
    bool isDbNull = false;
    bool isNull = false;

    if(obj.GetType() == typeof(DBNull))
        isDbNull = true;

    if (obj == null)
        isNull = true;

    if ((isNull || isDbNull) == false)
        return obj.ToString();

    if (nullOption == NullOptions.ConvertDbNullsToNulls)
    {
        return null;
    }
    else
    {
        return string.Empty;
    }
}

Example

object obj = DBNull.Value;
MessageBox.Show(obj.ToString(NullOptions.ConvertAllNullsToEmpty));
MessageBox.Show(obj.ToString(NullOptions.ConvertDbNullsToNulls));

Author: Hadi Lababidi

Submitted on: 19 feb 2010

Language: C#

Type: System.Object

Views: 2869