Advertisement
James-Ko

c-sharp_null-coalescing_bug

Mar 14th, 2015
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. using System;
  2. using Newtonsoft.Json;
  3.  
  4. namespace Test {
  5.         public class Program {
  6.                 public static void Main() {
  7.                         string json = "{ \"phones\": { \"personal\": null }, \"birthday\": null }";
  8.                         dynamic d = JsonConvert.DeserializeObject(json);
  9.                        
  10.                         Console.WriteLine(d.phones.personal == null);
  11.                        
  12.                         string s = ""; s += (d.phones.personal ?? "default");
  13.                         Console.WriteLine(s + " " + s.Length);
  14.                        
  15.                         string ss = d.phones.personal;
  16.                         string sss = ""; sss += (ss ?? "default");
  17.                         Console.WriteLine(sss + " " + sss.Length);
  18.                        
  19.                         Console.WriteLine(d.birthday == null);
  20.                        
  21.                         string s4 = ""; s4 += (d.birthday ?? "default");
  22.                         Console.WriteLine(s4 + " " + s4.Length);
  23.                        
  24.                         string s5 = d.birthday;
  25.                         string s6 = ""; s6 += (s5 ?? "default");
  26.                         Console.WriteLine(s6 + " " + s6.Length);
  27.                        
  28.                         //works, but verbose
  29.                         string s7 = "";
  30.                         s7 += (d.birthday != null ? d.birthday : "default");
  31.                         Console.WriteLine(s7 + " " + s7.Length);
  32.                        
  33.                         d = null;
  34.                        
  35.                         //also works
  36.                         string s8 = d ?? "default";
  37.                         Console.WriteLine(s8 + " " + s8.Length);
  38.                 }
  39.         }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement