Check If Class Property Is Not Null Before Calling Any Public Class Method

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

What is the best way to know if all the variables in a Class are null?

Try something like this:

public boolean checkNull() throws IllegalAccessException {
for (Field f : getClass().getDeclaredFields())
if (f.get(this) != null)
return false;
return true;
}

Although it would probably be better to check each variable if at all feasible.

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

How check whether class members are not null or empty

Using a dictionary based store for your properties is probably the easiest way of doing this:

public class MyClass
{
private IDictionary<String, String> _store;

public MyClass()
{
_store = new Dictionary<String, String>();
}

public string MyProp1 {
get { return GetOrDefault("MyProp1"); }
set { _store["MyProp1"] = value; }
}
public string MyProp2 {
get { return GetOrDefault("MyProp2"); }
set { _store["MyProp2"] = value; }
}

public Boolean HasData()
{
return _store.Any(x => !String.IsNullOrWhiteSpace(x.Value));
}

public Boolean IsEmpty()
{
return _store.All(x => String.IsNullOrWhiteSpace(x.Value));
}

private String GetOrDefault(String propertyName)
{
if (_store.ContainsKey(propertyName))
{
return _store[propertyName];
}

return String.Empty;
}
}

Another method for doing this would be to compare it with a default instance:

public class MyClass
{
public string MyProp1 { get; set; }
public string MyProp2 { get; set; }

public static readonly MyClass Empty = new MyClass();

public Boolean HasData()
{
return !Empty.Equals(this);
}

public Boolean IsEmpty()
{
return Empty.Equals(this);
}
}

C# elegant way to check if a property's property is null

In C# 6 you can use the Null Conditional Operator. So the original test will be:

int? value = objectA?.PropertyA?.PropertyB?.PropertyC;

Using a method for a null class

In whatever code that calls t.p() you should check if t is null. You shouldn't be calling methods on a null instance.

Regarding the second part of your question, no it is not possible to set a default method that will be called if the instance of that object is null.

I should point out that there is also the Null Object Pattern, that, depending on the exact circumstances of usage may help. I would not use it as replacement for null checks though. I've found the pattern useful in some cases.



Related Topics



Leave a reply



Submit