开发者

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 does开发者_运维问答nt seem to work.


Have you tried checking against DBNull.Value


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


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


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?


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; }
}


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())))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜