This question already has answers here:
Best and fastest way to check if an object is null [duplicate]
(6 answers)
Closed 9 years ago.
What is the most efficient way to check for null references on objects? I have seen various code samples that have different ways of checking so of the following which is the most efficient or the one that it is considered best practice to use?
Object.ReferenceEquals(item, null)
item == null
item != null
Object.Equals(item, null)
thanks
Object.ReferenceEquals(item, null) compare references and equals to item == null.
Object.Equals(item, null) compare references for reference types and bitwise for value types, but in reflector it's equal to (item == null) || ((item != null && null != null) && item.Equals(null)).
item != null code not always equals to !(item == null), but of course result should be equal.
item == null code not equals to null == item, it's similar to typeof(item).Equals(object) and object.Equals(typeof(item)) method calls.
It differ because you can override !=, ==, Equals.
Use methods with known implementation, null == item is better to code, but harder to read.
Object.ReferenceEquals(null, item) may be faster or not.
P.S. use string.IsNullOrEmpty(item) too
For comparing to null, I'd use == or != always, because for null it should always give the same result as ReferenceEquals and Equals anyway (so no need for the extra code).
Edit: It's true that == could be overridden to give a wrong result for null (i.e., true) but that means the override is buggy. To make the code readable I would stick with == and !=.
Updated answer
As of C# 7.0 is you can use:
item is null
should be the simplest and most foolproof way. It's same as ReferenceEquals check.
Old answer:
1)
Object.ReferenceEquals(item, null)
This is a good way. Not as concise as I would love, but still great and tells u the intent exactly.
2)
item == null
item != null
There is nothing wrong with this (which is the most elegant) if you are sure == and subsequently != is overloaded correctly. Its easy to write (overload) bad equality operators (and often done). But the real trouble is when you are trying to overload == operator in a class (lets say of value semantic). You cant use == for null checks inside == overloading function of the class since that will cause an infinite recursion. To have one consistent style, I rely on something else.
3)
Object.Equals(item, null)
Again it internally does a ReferenceEquals so there is not much point, but if it semantically makes more sense to you, then go with this.
4)
My approach is to do
(object)item == null
upon which I'm relying on object's own equality operator which can't go wrong. Not so readable so I just wrap in a custom extension method and an overload:
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null;
}
public static bool IsNull<T>(this T? obj) where T : struct
{
return !obj.HasValue;
}
It makes more sense since I will need to check against DBNulls too often. So now I have one consistent style all over!
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null || obj == DBNull.Value;
}
(Do not take off the (object) casting as that's what will prevent infinite recursion when overloading == as stated before)
Additionally the constraint prevents IsNull on value types. Now its as sweet as calling
object obj = new object();
Guid? guid = null;
bool b = obj.IsNull(); // false
b = guid.IsNull(); // true
2.IsNull(); // error
I also have found (object)item == null is very very very slightly faster than Object.ReferenceEquals(item, null) or object.Equals(,) for that matter, but only if it matters (I'm currently working on something where I've to micro-optimize everything!).
To see a complete guide on implementing equality checks, see What is "Best Practice" For Comparing Two Instances of a Reference Type?
As an extra, don't forget code contracts in .NET 4.0!
System.Diagnostics.Contracts.Contract.Requires(item != null);
Which is not only nice and clear, but allows compile time checking. See Code Contracts in msdn.
ReferenceEquals is equivalent to (object)o1==(object)o2. It may be faster than o1==o2 if the equality operator is overloaded. Object.Equals is probably a bit slower.
The difference between == and != isn't performance, but how your program should look like. They can be a bit slower if the == and != operator are overloaded.
But I don't think the performance difference between them matters at all. I'd choose the one that's easiest to read. And that's usually == or !=.
If I throw an exception I usually use == as in:
if(o == null)
throw new ...;
If null results in a no-op then usually != is appropriate
if(x != null)
{
...
}
I always use
item != null
but this is harder to read than
item == null
Object.ReferenceEquals is used to check whether two objects are the same instance.
First 2 are the same effectively.
The last however does not only do a reference check, and should not be used for null checking.
Related
I apologize if this question is a bit obsessive but I do like my code not to have any wiggly lines underneath it where resharper is telling me off.
I have a generic list:
var permissions = new List<Permission>();
at some point in the code I need to test the first element:
if (permissions.First().ImportID == this.ImportId)
{
// do stuff
}
Resharper (rightly) complains that permissions could be null, so I take its advice and add a check in:
if (permissions != null && permissions.First().ImportID == this.ImportId)
{
// do stuff
}
Now I realise that I need to protect against the list being empty so I add a check for any in there too:
if (permissions != null && permissions.Any() && permissions.First().ImportID == this.ImportId)
{
// do stuff
}
and life is good, the code works & resharper is quiet. Realising that the null + any() check is going to be used quite often I add an extension method:
public static bool IsEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
return true;
return !source.Any();
}
The only problem is now when I use this:
if (!permissions.IsEmpty() && permissions.First().ImportID == this.ImportId)
Resharper starts moaning again "Possible null assignment to entity marked with "NotNull" attribute".
So, is there a way to let resharper know that permissions will never be null after IsEmpty() has executed (in the same way it understands what != null does) or is my only option to ignore the message.
I suspect you can use a R# annotation for this. Something like:
[ContractAnnotation("null => true")]
public static bool IsEmpty<T>(this IEnumerable<T> source)
{
return source == null || !source.Any();
}
I believe that should give R# enough information to work out that you're not trying to use a null reference if IsEmpty returns false.
I had an idea about creating a bool isNull that can be used pretty much ambiguously wherever needed. The original idea was as follows (pseudo-code only):
bool isNull(var test)
{
if (test == null || DBNull || string.Empty)
return true;
else
return false;
}
But this doesn't work, as var is not recognised here. Instead, it appears to be assumed that var refers to a type... well I, of course, don't have a type for var!
What do I do to get around this? Or, perhaps the question I should be asking, Is this a good idea at all?
Why don't you use object ?
bool isNull(object test)
{
if (test == null || test == DBNull.Value)
return true;
else
return false;
}
For strings, I would use string.IsNullOrEmpty method.For other types, especially when you are dealing with databases this function can be useful.
Your code isn't working because var will be resolved at compile-time.
You could use object or dynamic as type. dynamic will be resolved at run-time
Well, I have the following query that I use to search a LIST with the text that the user has filled.
It's only one textbox that search in all these fields below, it's working but when one of these fields is null, it's throwing a null reference exception, how can I avoid that?
List<REP_MEDIDORDISPLAY> SearchFiltered = new List<REP_MEDIDORDISPLAY>();
if (filter != String.Empty)
{
SearchFiltered.Clear();
foreach (String Item in filter.Split(';').ToList<String>())
{
SearchFiltered.AddRange(Medidores.Where(x => x.Data_TOI.Contains(Item.Trim()) ||
x.Elemento.ToUpper().Contains(Item.Trim()) ||
x.Fase.ToUpper().Contains(Item.Trim()) ||
x.ID.ToUpper().Contains(Item.Trim()) ||
x.KdKe.ToUpper().Contains(Item.Trim()) ||
x.N_Equipamento.ToUpper().Contains(Item.Trim()) ||
x.Status.ToUpper().Contains(Item.Trim()) ||
x.Tensao.ToUpper().Contains(Item.Trim())));
}
}
I hope you guys can help me. thanks.
By checking for null first:
(x.Elemento != null && x.Elemento.ToUpper().Contains(Item.Trim())) ||
// etc
Of course you should also calculate Item.Trim() just once and reuse this value for all tests rather than trimming as many times as there are fields.
You can add null check to each of the properties. Example:
From
x.Fase.ToUpper().Contains(Item.Trim()) ||
To
(x.Fase != null && x.Fase.ToUpper().Contains(Item.Trim())) ||
Maybe you should introduce something like a null object. This object is empty and will therefore always return false on every query against it.
If you implement nullchecks for every property on that object your code will rot over time. And you are gonna have a bad time.
There are many ways to do what you are doing, some more elegant perhaps.
One simple way could be to override the ToString method in the object in the Medidores sequence and use that for the comparison.
Something like this:
class Medidor {
... properties
public override string ToString() {
return Data_TOI + Elemento ... etc
}
}
And then you could compare against that instead.
SearchFiltered.AddRange(
Medidores.Where(x =>
x.ToString()
.IndexOf(Item.Trim(), 0, StringComparison.InvariantCultureIgnoreCase) != -1
);
I'm using IndexOf as it has an overload that takes StringComparison.InvariantCultureIgnoreCase, which ignores casing among other things.
The reason why I think this approach is preferred to what you have now, is that the Meridor object itself is responsible for what fields are included in the ToString method. Maybe it can improve readability and maintainability.
a ?? b
If a is not null => returns a.
Else (a is null) => returns b.
I want to simulate something like its inverse (AFAIK there is no operator to do this):
If a is null => return a.
Else (a is not null) => returns b.
The idea is that b would be the result of a function that receives a and needs to avoid null parameters. Like this: a XX fn(a) where XX would be the operator (if it exists).
My only two variants are:
a == null ? a : fn(a)
a == null ? null : fn(a)
Is there any way to simplify this code?
Not sure exactly what you're trying to accomplish? Something like this?
TResult NullFn<TParam, TResult>(TParam a, Func<TParam, TResult> method)
{
if(a == null) return null;
return method(a);
}
...
var result = NullFn(a, a => fn(a))
But the best solution IMHO would be to just have fn return null if it is passed a null value.
EDIT:
The method at the top is only an example. You might want to use something like this in a situation where you've got a LOT of the same operation over and over again in a specific area and you can't change fn because it would make is easier to focus on the rest of the code and there's a chance you might want to alter the null-handling behavior for all your operations at once in the future. (I'm assuming that is the case because you're asking in the first place.) But I wouldn't use this across an entire application because it isn't clear what's happening if you don't have the NullFn function right in front of you.
Whats wrong with simple condition?
if (a != null) b = fn(a);
Another option - add a condition to your method:
public B fn(A a)
{
if (a == null)
return null;
return new B();
}
Personally I would prefer
(a != null) ? fn(a) : null
because I think it makes the intention more obvious, but I can not think of a way to simplify that much. You could use an extension method if you like.
a.CallIfNotNull(fn)
with the following extension method
internal static T CallIfNotNull<T>(this T value, Func<T, T> function)
where T : class
{
return (value != null) ? function(value) : null;
}
Not really better but probably less error prone and easier to type given IntelliSense.
(Is assumed the function returns a value of the same type as the argument as the question suggests.)
If you have T a; and T fn(T a); using the same user-defined type T, then you can write a && fn(a) and it will expand to T.False(a) ? a : T.&(a, fn(a)).
You've answered your own question with the ?: implementations at the bottom.
The only improvement i would suggest is to wrap the functionality in a method that makes it cleaner and less error prone to do.
object SafeB(object a)
{
return a==null ? a : b(a);
}
The compiler will probably inline this so you won't lose performance.
You may even be able to implement it as an extension method of the class that provides b so that it becomes an even more integrated solution.
I have the following line of code below. Is there a method that can check team, DivisionTeam, Team, Coordinator, Profile, Address, and the last property StateRegion for null instead of doing it for every property?
if(team.DivisionTeam.Team.Coordinator.Profile.Address.StateRegion != null)
Currently in C#, you can't, you have to individually check each property for null.
May be you are looking for ".?" operator, but its not there in C# 4.0, Check out this post and the response from Eric Lippert: Deep null checking, is there a better way?
You should check the following article: Chained null checks and the Maybe monad. This is, IMO, the cleanest way to actually "do" what you are asking for.
And, no, there is no inbuilt way in C# to do this directly.
In C# 6.0 you can do it in just one string:
var something = team?.DivisionTeam?.Team?.Coordinator?.Profile?.Address?.StateRegion;
Check this article for further reading: null-conditional operator.
Here is a sample
private bool IsValidTeam(Team team)
{
bool result = false;
if (team != null)
if (team.DivisionTeam != null)
if (team.DivisionTeam.Team != null)
if (team.DivisionTeam.Team.Coordinator != null)
if (team.DivisionTeam.Team.Coordinator.Profile != null)
if (team.DivisionTeam.Team.Coordinator.Profile.Address != null)
if (team.DivisionTeam.Team.Coordinator.Profile.Address.StateRegion != null)
result = true;
return result;
}
Check my answer here:
https://stackoverflow.com/a/34086283/4711853
You could simply write a small extension method, which afford you to write chained lambda like this:
var value = instance.DefaultOrValue(x => x.SecondInstance)
.DefaultOrValue(x => x.ThirdInstance)
.DefaultOrValue(x => x.Value);