I would like to prevent further processing on an object if it is null.
In the following code I check if the object is null by either:
if (!data.Equal
The problem in this case is not that data
is null. It is that dataList
itself is null.
In the place where you declare dataList
you should create a new List
object and assign it to the variable.
List<object> dataList = new List<object>();
in C# > 7.0 use
if (obj is null)
...
This will ignore any ==
or !=
defined by the object (unless of course you want to use them ...)
For not null use if (obj is object)
and from C# 9 you can also use if (obj is not null)
I did more simple (positive way) and it seems to work well.
Since any kind of "object" is at least an object
if (MyObj is Object)
{
//Do something .... for example:
if (MyObj is Button)
MyObj.Enabled = true;
}
As of C# 8 you can use the 'empty' property pattern (with pattern matching) to ensure an object is not null:
if (obj is { })
{
// 'obj' is not null here
}
This approach means "if the object references an instance of something" (i.e. it's not null).
You can think of this as the opposite of: if (obj is null)...
. which will return true when the object does not reference an instance of something.
For more info on patterns in C# 8.0 read here.
C# 6 has monadic null checking :)
before:
if (points != null) {
var next = points.FirstOrDefault();
if (next != null && next.X != null) return next.X;
}
return -1;
after:
var bestValue = points?.FirstOrDefault()?.X ?? -1;
As of C# 9 you can do
if (obj is null) { ... }
For not null use
if (obj is not null) { ... }
If you need to override this behaviour use ==
and !=
accordingly.