developer
developer

Reputation: 5478

Empty object check

Is there a way to know if all the properties in an object are empty. My object represents fields from database and I want to know if a particular record is present or not. NULL doesnt seem to work.

Upvotes: 3

Views: 9858

Answers (6)

I've found occasions where using just a check with DBNull isn't enough. Maybe not the purest approach but a temporary check as a string seems to do the trick. Like so:

    if ((DBNull.Value != field) &&
        (!string.IsNullOrWhiteSpace(field.ToString())))

Upvotes: 0

Justin
Justin

Reputation: 4072

A lot of languages use a method or property called IsEmpty for this kind of check. During the hydration phase of the object set a boolean flag that specifies if the object is empty or not. Then you can simply use the property or method elsewhere to check for empty objects.

ie

During hydration

bool _isEmpty = false;

if( prop1 is empty && prop2 is empty )
{
  _isEmpty = true;
}
else
{
  _isEmpty = false;
}

Then use an IsEmpty property

IsEmpty
{
   get { return _isEmpty; }
}

Upvotes: 0

Pat
Pat

Reputation: 16911

If your object represents fields from database, then it's probably a collection. If so, you can most likely use an extension method like myCollection.Any() to see if there are any objects inside the collection. Is that what you are asking for?

Upvotes: 0

John Saunders
John Saunders

Reputation: 161831

If the record is not present, then why would you have an object to represent it?

Upvotes: 0

EgorBo
EgorBo

Reputation: 6142

You can use reflection:

public static bool IsEmptyEntity<T>(T obj)
{
    foreach (var property in typeof(T).GetProperties())
        if (property.GetValue(obj, null) != null)
            return false;
    return true; 
}

Usage:

    public class MyTestEntity
    {
        public string Str { get; set; }
        public int? Int { get; set; }
    }

MyTestEntity test = new MyTestEntity();
var empty = IsEmptyEntity(test); //returns true

Upvotes: 3

Josh Mein
Josh Mein

Reputation: 28665

Have you tried checking against DBNull.Value

Upvotes: 5

Related Questions