C # Null distribution statement / conditional expression and if blocks

The null distribution operator / conditional access expression included in looks like a pretty handy feature. But I'm curious if this will help solve the problem of checking whether the child is non-zero, and then calls the boolean method for the specified child inside the if block:

public class Container<int>{ IEnumerable<int> Objects {get;set;} } public Container BuildContainer() { var c = new Container(); if (/* Some Random Condition */) c.Objects = new List<int>{1,2,4}; } public void Test() { var c = BuildContainer(); //Old way if ( null != c && null != c.Objects && c.Objects.Any()) Console.Write("Container has items!"); //C# 6 way? if (c?.Object?.Any()) Console.Write("Container has items!"); } 

Will c?.Object?.Any() compile? If the short-circuited distribution operator (suppose the right term) is zero, you have if (null) , which is not valid.

Will the C # team solve this problem, or am I missing the intended use case for an empty distribution operator?

+11
null c # language-features
Sep 04 '14 at 13:38 on
source share
2 answers

This will not work. You can simply skip the explanation and see the code below :)

How do you know the operator ?. returns null if the child is null. But what happens if we try to get a member that does not contain NULL, like the Any() method that returns bool ? The answer is that the compiler will "wrap" the return value in Nullable<> . For example, Object?.Any() will give us bool? (which is Nullable<bool> ), not bool .

The only thing that does not allow us to use this expression in an if is that it cannot be implicitly executed in bool . But you can do the comparison explicitly, I prefer to compare with true as follows:

 if (c?.Object?.Any() == true) Console.Write("Container has items!"); 

Thanks to @DaveSexton there is another way:

 if (c?.Object?.Any() ?? false) Console.Write("Container has items!"); 

But for me, comparison with true seems more natural :)

+27
Sep 04 '14 at 13:54 on
source share

The null conditional operator returns null or the value at the end of an expression. For value types, It will return the result in Nullable<T> , so in your case it will be Nullabe<bool> . If we look at an example in a document for Upcoming Functions in C # (listed here ), it has an example:

 int? first = customers?[0].Orders.Count(); 

In the above example, instead of int , a Nullable<int> will be returned. For bool it will return a Nullable<bool> .

If you try the following code in Visual Studio "14" CTP :

 Nullable<bool> ifExist = c?.Objects?.Any(); 

The result of the above line will be Nullable<bool> / bool? . Later you can make a comparison, for example:

Using the zero-bound operator

  if (c?.Object?.Any() ?? false) 

Using the Nullable<T>.GetValueOrDefault Method

 if ((c?.Objects?.Any()).GetValueOrDefault()) 

Using comparison with true

 if (c?.Objects?.Any() == true) 
+4
Sep 04 '14 at 13:57 on
source share



All Articles