Checking if an object is null in C#
It's not data
that is null
, but dataList
.
You need to create one with
public List<Object> dataList = new List<Object>();
Even better: since it's a field, make it private
. And if there's nothing preventing you, make it also readonly
. Just good practice.
Aside
The correct way to check for nullity is if(data != null)
. This kind of check is ubiquitous for reference types; even Nullable<T>
overrides the equality operator to be a more convenient way of expressing nullable.HasValue
when checking for nullity.
If you do if(!data.Equals(null))
then you will get a NullReferenceException
if data == null
. Which is kind of comical since avoiding this exception was the goal in the first place.
You are also doing this:
catch (Exception e)
{
throw new Exception(e.ToString());
}
This is definitely not good. I can imagine that you put it there just so you can break into the debugger while still inside the method, in which case ignore this paragraph. Otherwise, don't catch exceptions for nothing. And if you do, rethrow them using just throw;
.
C# Checking if Object is Null
It is possible that the
try
block will never assign a value toro
and thus it will be unassigned outside of try block. To fix that, assign a value:RootObject ro = null;
Since
ro
could benull
, you need to check for that in yourif
statement before you try to access a member:if (ro != null && ro.Region != null)
{
Row.Region = ro.Region;
Row.SubRegion = ro.Subregion;
}
How to check if one value of an object is null
You can gather all your strings into an array and then run .Any()
method:
if (new[] { obj.string1, obj.string2, obj.string3 }.Any(string.IsNullOrWhiteSpace))
{
}
Alternatively you can use reflection (which will affect your code's performance), to scan all the strings of your object and check your condition:
var anyEmpty = obj.GetType().GetProperties()
.Any(x => x.PropertyType == typeof(string)
&& string.IsNullOrWhiteSpace(x.GetValue(obj) as string));
Checking if an object is null
It depends on the purpose of the function, in your function's case it looks like you will be using it to insert the object into a repository therefore passing a null object into a repository should throw an exception and not just silently fail.
You should check for null and throw an ArgumentException
if the parameter is null.
public async Task TestFunction(TestObject obj)
{
if(obj == null) {
throw new ArgumentException("obj cannot be null");
}
obj.name = "Test Name";
repository.Insert(obj);
}
However there are cases where you could have a function that can accept a null object possibly returning a default value if you do pass it in.
Just don't write code like this:
public async Task TestFunction(TestObject obj)
{
if(obj != null) {//if null don't do anything
obj.name = "Test Name";
repository.Insert(obj);
}
}
This method will do nothing and if the developer calling it didn't realise that the object passed was null then it will fail silently without letting the developer know what happened.
C# how to check for null. (value is null) or (null == value). Can we use `is` operator instead of == operator
Yes, you can use the is
operator with the constant pattern of null
to check whether a reference (or nullable value type value) is null or not.
Indeed, in C# 7 I would say that using is null
is the most idiomatic way of testing for a null value, because it doesn't use any user-defined operators. Consider this:
string x = GetStringFromSomewhere();
if (x == null) { } // Option 1
if (x is null) { } // Option 2
Here, option 1 will call the ==
operator overload defined in string
. While that should do what you want (and I expect the JIT compiler will optimize it pretty heavily), it's not like you particularly want to do that - you just want to test whether the value of x
is a null reference. That's exactly what option 2 does.
So yes, you can use is null
for all null checking if you don't have types that perform odd custom comparisons. It's possible to write a class such that x == null
and x is null
would give different results, but that would almost always be a design (or implementation) problem.
There's no concept of an object being "empty" - and indeed it's not the object that's null. Leaving nullable value types aside for now, it's a reference that's null, not an object - a null value indicates the absence of an object. It's worth distinguishing carefully between objects and references in your mind.
Some specific object types have a concept of "empty" - for example, a string can be empty, or a collection - but those types have specific ways of testing for emptiness. There's no general concept of an object being empty.
IsNullOrEmpty with Object
a null string is null, an empty string is ""
isNullOrEmpty requires an intimate understanding about the implementation of a string. If you want one, you can write one yourself for your object, but you have to make your own definition for whether your object is "empty" or not.
ask yourself: What does it mean for an object to be empty?
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.
Checking for empty or null Liststring
Try the following code:
if ( (myList!= null) && (!myList.Any()) )
{
// Add new item
myList.Add("new item");
}
A late EDIT because for these checks I now like to use the following solution.
First, add a small reusable extension method called Safe():
public static class IEnumerableExtension
{
public static IEnumerable<T> Safe<T>(this IEnumerable<T> source)
{
if (source == null)
{
yield break;
}
foreach (var item in source)
{
yield return item;
}
}
}
And then, you can do the same like:
if (!myList.Safe().Any())
{
// Add new item
myList.Add("new item");
}
I personally find this less verbose and easier to read. You can now safely access any collection without the need for a null check.
And another EDIT, which doesn't require an extension method, but uses the ? (Null-conditional) operator (C# 6.0):
if (!(myList?.Any() ?? false))
{
// Add new item
myList.Add("new item");
}
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));
Related Topics
How to Implement an Exhaustmap Handler in Rx.Net
How to Draw a Rounded Rectangle as the Border for a Rounded Form
How to Programmatically Click a Button in Wpf
Why Does the Lock Object Have to Be Static
Method Overloading VS Optional Parameter in C# 4.0
How to Forcefully Propagate Role Changes to Users with ASP.NET Identity 2.0.1
Display Unicode Characters in Converting HTML to PDF
C# Create/Modify/Read .Xlsx Files
Add Shape Information to a Listview When Its Created
Mongodb Gridfs with C#, How to Store Files Such as Images
How to Install a Certificate into the Local MAChine Store Programmatically Using C#