How to Check All Properties of an Object Whether Null or Empty

How to check all properties of an object whether null or empty?

You can do it using Reflection

bool IsAnyNullOrEmpty(object myObject)
{
foreach(PropertyInfo pi in myObject.GetType().GetProperties())
{
if(pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(myObject);
if(string.IsNullOrEmpty(value))
{
return true;
}
}
}
return false;
}

Matthew Watson suggested an alternative using LINQ:

return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));

Checking if Object has null in every property

EDIT

This answer has received some votes in the last time, so I decided to improve it a little, adding simple caching so that ArePropertiesNotNull does not retrieve the properties every time it is called, but rather only once for every type.

public static class PropertyCache<T>
{
private static readonly Lazy<IReadOnlyCollection<PropertyInfo>> publicPropertiesLazy
= new Lazy<IReadOnlyCollection<PropertyInfo>>(() => typeof(T).GetProperties());

public static IReadOnlyCollection<PropertyInfo> PublicProperties => PropertyCache<T>.publicPropertiesLazy.Value;
}

public static class Extensions
{
public static bool ArePropertiesNotNull<T>(this T obj)
{
return PropertyCache<T>.PublicProperties.All(propertyInfo => propertyInfo.GetValue(obj) != null);
}
}

(Old answer below.)


You could use reflection as proposed by Joel Harkes, e.g. I put together this reusable, ready-to-use extension method

public static bool ArePropertiesNotNull<T>(this T obj)
{
return typeof(T).GetProperties().All(propertyInfo => propertyInfo.GetValue(obj) != null);
}

which can then be called like this

var employee = new Employee();
bool areAllPropertiesNotNull = employee.ArePropertiesNotNull();

And now you can check the areAllPropertiesNotNull flag which indicates whether all properties are not null. Returns true if all properties are not null, otherwise false.



Advantages of this approach

  • It doesn't matter whether or not the property type is nullable or not for the check.
  • Since above method is generic, you can use it for any type you want and don't have to write boilerplate code for every type you want to check.
  • It is more future-proof in case you change the class later. (noted by ispiro).

Disadvantages

  • Reflection can be quite slow, and in this case it is certainly slower than writing explicit code as you currently do. Using simple caching (as proposed by Reginald Blue will remove much of that overhead.

In my opinion, the slight performance overhead can be neglected since development time and repetition of code are reduced when using the ArePropertiesNotNull, but YMMV.

How to check if every properties in an object are null

You can use Object.values to convert the object into array and use every to check each element. Use ! to negate the value.

let report = {  property1: null,  property2: null,}
let result = !Object.values(report).every(o => o === null);
console.log(result);

Easiest way to check if property is null or empty in java

Write a method isNullOrEmpty(String):

static boolean isNullOrEmpty(String s) {
return s == null || s.trim().isEmpty()
// Or return s == null || s.isBlank(); in Java 11+
}

So you can write:

return isNullOrEmpty(account.getAccesskeyid())
|| isNullOrEmpty(account.getAccount())
/* etc */;

I consider this preferable to doing something that involves constructing streams or lists, because it's just simple: it's using very basic language features that are easily understandable by even a novice programmer.

In addition, it avoids evaluating all of the fields (e.g. passing String... ss to isNullOrEmpty, and then doing something on the array) because it short-circuits, in that it will stop as soon as it finds the first null or empty string.

It also does not require creation of any objects (like the implicit array, or a List in the case of Arrays.asList(...)) that are simply artefacts of invoking the method: trim() does potentially create objects, but this is "useful" work, insofar as this is necessary to evaluate the condition.

Determining if all attributes on a javascript object are null or an empty string

Create a function to loop and check:

function checkProperties(obj) {
for (var key in obj) {
if (obj[key] !== null && obj[key] != "")
return false;
}
return true;
}

var obj = {
x: null,
y: "",
z: 1
}

checkProperties(obj) //returns false

How to check all properties of an class whether null or empty?

Something like this (checking for null, note, that non-string property can be empty):

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
// Or false, or throw an exception
if (Object.ReferenceEquals(null, instance))
return true;

//TODO: elaborate - do you need public as well as non public properties? Static ones?
var properties = instance.GetType().GetProperties(
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic);

foreach (var prop in properties) {
if (!prop.CanRead) // <- exotic write-only properties
continue;
else if (prop.PropertyType.IsValueType) // value type can't be null
continue;

Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING properties for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;
}

return true;
}

Edit: the updated example provided shows, that you want to check fields as well as properties, not properties alone; in that case:

// You don't need generic, Object is quite enough 
public static bool Check(Object instance) {
// Or false, or throw an exception
if (Object.ReferenceEquals(null, instance))
return true;

//TODO: elaborate - do you need public as well as non public field/properties? Static ones?
BindingFlags binding =
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;

// Fields are easier to check, let them be first
var fields = instance.GetType().GetFields(binding);

foreach (var field in fields) {
if (field.FieldType.IsValueType) // value type can't be null
continue;

Object value = field.GetValue(field.IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING fields for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;

// Extra condition: if field is of "WS_IN_" type, test deep:
if (field.FieldType.Name.StartsWith("WS_IN_", StringComparison.OrdinalIgnoreCase))
if (!Check(value))
return false;
}

// No null fields are found, let's see the properties
var properties = instance.GetType().GetProperties(binding);

foreach (var prop in properties) {
if (!prop.CanRead) // <- exotic write-only properties
continue;
else if (prop.PropertyType.IsValueType) // value type can't be null
continue;

Object value = prop.GetValue(prop.GetGetMethod().IsStatic ? null : instance);

if (Object.ReferenceEquals(null, value))
return false;

//TODO: if you don't need check STRING properties for being empty, comment out this fragment
String str = value as String;

if (null != str)
if (str.Equals(""))
return false;
}

return true;
}

Check if properties of a TypeScript object are all empty

By using Object.keys() you can do it as following

var objectProp = {  property1: [],  property2: [],}
if(Object.keys(objectProp).every(key => objectProp[key] && objectProp[key].length === 0)){ console.log('All is empty')}

Check if any property of class is null

You're checking if the properties themselves are null (which will never be true), not the values of the properties. Use this instead:

bool isNull = objRequirement.GetType().GetProperties()
.All(p => p.GetValue(objRequirement) != null);

Check if all the properties of class are null

You could make a property IsInitialized, that does this internally:

public bool IsInitialized
{
get
{
return this.CellPhone == null && this.Email == null && ...;
}
}

Then just check the property IsInitialized:

if (myUser == null || myUser.IsInitialized)
{ ... }

Another option is the use of reflection to walk over and check all properties, but it seems overkill to me. Also, this gives you the freedom to deviate from the original design (when you choose all properties, except one should be null for example).

Array check Empty or Null by all properties in object

I think you're looking for the some method (instead of forEach and find), which calls a callback for each element in the array and stops the first time the callback returns true.

const checkEmtry = () => data.some(e => Object.values(e).some(x => x === null || x === ""));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^−−−−−−−−−−−−−−−−−−−−−−−^^^^

Live Example:

const data = [
{
name: "Kris",
Tel: 000000,
address:""
},
{
name: "Mark",
Tel: 111111,
address:"USA"
},
{
name: "Charie",
Tel: null,
address:""
},
];

const checkEmtry = () => data.some(e => Object.values(e).some(x => x === null || x === ""));

console.log(checkEmtry()); // true


Related Topics



Leave a reply



Submit