Is there a way to Imitate C# 6 Null-Conditional operator in C# 5

假装没事ソ 提交于 2019-12-04 08:57:26

Well, you can use an extension method that receives an accessor delegate and only executes it if the item isn't 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 like this:

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

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

Like this. 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,             
 });

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

What you can do, though, is to create an extension method (or a helper method, static one, preferably) or an instance method working with the properties.

Or, as someone suggested, just use the conditional statement (inline or explicit). But that's not what you're looking for, of course.

One more method (and it's not at all recommendable) is to surround the assignment with a try-catch. But that's really baaad solution and I only mention it for completeness' sake.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!