Check All Child Properties For Null in C# - c#

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

Related

What is this operator, "??" [duplicate]

This question already has answers here:
What do two question marks together mean in C#?
(19 answers)
Closed 5 years ago.
I'm on an upgrade project and recently began experiencing issues with the upgraded version of a DLL. I decompiled the original dll and found the following if statement:
if (fieldConfiguration == null && Context.ContentDatabase != null)
{
Item obj = Context.ContentDatabase.SelectSingleItem(
string.Format("//*[##templateid='{0}' and ##key='{1}']",
(object) TemplateIDs.TemplateField, (object) fieldName));
}
I then decompiled the upgraded version of the DLL and the statement was as follows:
if (fieldConfiguration == null && (Context.ContentDatabase ?? Context.Database) != null)
{
Item obj = Context.ContentDatabase.SelectSingleItem(
string.Format("//*[##templateid='{0}' and ##key='{1}']",
(object) TemplateIDs.TemplateField, (object) fieldName));
}
I was able to step through the code by decompiling the DLLs with dotPeek and using the dotPeek symbol server functionality. I can see that the code is failing when using the upgrade DLL because Context.ContentDatabase is null. What I don't understand is how that double ternary operator is evaluated. Could someone clarify for me what's going on there? It seems as though the creators of this assembly wanted a null check for Context.ContentDatabase but may have made a mistake. Thanks for the help!
Well yeah that looks like an error. The code is looking whether Context.ContentDatabase or Context.Database aren't null, and then continues to use the former, even if it was null.
The code should look like this:
var database = Context.ContentDatabase ?? Context.Database;
if (fieldConfiguration == null && database != null)
{
Item obj = database.SelectSingleItem(
string.Format("//*[##templateid='{0}' and ##key='{1}']",
(object) TemplateIDs.TemplateField, (object) fieldName));
}
Where it stores the database in a separate variable using the null-coalescing operator and then operates on that, if it isn't null.
So you should contact the team who provides this library and file a bug with them.
(Context.ContentDatabase ?? Context.Database) expressions end result is Context.ContentDatabase if Context.ContentDatabase is not null, otherwise it'll be Context.Database. The null-coalesce operator is a step forward to terse null checks.
Docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator
Assuming Context.ContentDatabase and Context.Database are same types. The below code should work.
var contentDatabase = Context.ContentDatabase ?? Context.Database;
if (fieldConfiguration == null && contentDatabase != null)
{
Item obj = contentDatabase.SelectSingleItem(
string.Format("//*[##templateid='{0}' and ##key='{1}']",
(object) TemplateIDs.TemplateField, (object) fieldName));
}

Resharper: Possible null assignment to entity marked with "NotNull" attribute

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.

What is the fastest way to get a property from an object after checking that the object isn't null?

What is the fastest way (in terms of minimizing the amount of code statements) to get a property from an object after checking that the object isn't null?
string s = null;
if (null != myObject)
{
s = myObject.propertyName;
}
For reference: Wait for future C# 6.0 feature for null checking with possible ?. syntax:
string result = obj?.ToString();
For now: Use ternary operator:
string result = obj != null ? obj.ToString() : null;
C# does not have a null-propagating operator (although it has been discussed a few times). Frankly, "faster" is not likely to be a factor here, as it will typically end up in the same (or similar enough) IL, but I tend to use:
string s = myObject == null ? null : myObject.PropertyName;
the situation you describe is only one scenario where the operator is useful. It's also handy to replace constructs like this:
if (value != null)
{
return value;
}
else
{
return otherValue;
}
Or
return value != null ? value : otherValue;
with
return value ?? otherValue;

Lambda expressions query null field

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.

What is good practice for null reference checks? [duplicate]

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.

Categories