Is there a way to emulate the C # 6 null-conditional statement in C # 5

I have a situation where I need to assign the properties of some objects inside the object initializer. Some of these objects may be null, and I need to access their properties, the problem is that there are too many of them, and using if / else is not very good.

Example

visits = visitJoins.AsEnumerable().Select(joined => new VisitPDV() { VisiteId = joined.Visite.VisiteId.ToString(), NomPointDeVente = joined.VisitePdvProduit.PointDeVente.NomPointDeVente, }); 

joined.VisitePdvProduit can be null, and the problem is that there are dozens of such assignments (I just took one to shorten the code)

C# 6 Null-Conditional operator is an ideal solution for this situation, the problem is that I am on C# 5 in this project, is there any way to simulate this?

+5
source share
3 answers

Well, you can use the extension method, which gets the accessor delegate and only executes it if the element is not null :

 public static TResult ConditionalAccess<TItem, TResult>(this TItem item, Func<TItem, TResult> accessor) where TResult : Class { if (item == null) { return null; } else { return accessor(item); } } 

You can use it, for example, as follows:

 NomPointDeVente = joined.VisitePdvProduit.ConditionalAccess(_ => _.PointDeVente.NomPointDeVente); 

You can easily create versions of this method for operations that do not return a value (i.e. bar.ConditionalAccess(_ => _.Foo()) ) or return value types.

+6
source

Like it. Ugly, but what had to be done.

  visits = visitJoins.AsEnumerable().Select(joined => new VisitPDV() { VisiteId = joined.Visite.VisiteId.ToString(), NomPointDeVente = (joined.VisitePdvProduit == null) ? null : joined.VisitePdvProduit.PointDeVente.NomPointDeVente, }); 
+1
source

If you are talking about a semi-very surprised operator ?, then no. There is no way to mimic the syntax.

However, you can create an extension method (or a helper method, static, preferably) or an instance method that works with properties.

Or, as someone suggested, just use a conditional statement (built-in or explicit). But that is not what you are looking for, of course.

Another method (and not recommended ) is to surround the job using try-catch. But this is really a baaad solution, and I only mention it for completeness.

0
source

Source: https://habr.com/ru/post/1237184/


All Articles