Search code examples
c#.net

How to check if an object contains a value?


I need to check if an object contains any value. The following function works fine if the object is a String type but I was looking to replace this with a generic way without checking for the type. Is there a way to do this?

public void SetValue(int id, object fieldData)
{
    if (fieldData!=null)
    {
        if (fieldData.GetType() == typeof(String) && fieldData.Equals(string.Empty))
        {
            return;
        }
    }
 
    SetLOValue(id, fieldData);
}

Solution

  • You can check for default types if you make it generic, but you have to be sure that's what you want. i.e. is 0 a valid number in your usage?

    if (fieldData == default(T))
    {
      return;
    }
    

    Alternatively, you could switch to Nullable types.

    if (fieldData.HasValue)...