Checking an empty object

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

+3
source share
6 answers

Have you tried checking on DBNull.Value

+5
source

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

Using:

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

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

, ?

0

object represents fields from database, , , . , , , , myCollection.Any(), , - . , ?

0

For this type of validation, many languages ​​use a method or property called IsEmpty. During the hydration phase of the object, a logical flag is set indicating whether the object is empty or not. Then you can simply use the property or method elsewhere to check for empty objects.

t

During hydration

bool _isEmpty = false;

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

Then use the property IsEmpty

IsEmpty
{
   get { return _isEmpty; }
}
0
source

I have found cases where using just checking with DBNull is not enough. It may not be the cleanest approach, but a temporary check like a string seems to do the trick. For instance:

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

Source: https://habr.com/ru/post/1738547/


All Articles