Tech Off Post

Single Post Permalink

View Thread: The opposite of ??
  • User profile image

    Actually, you can let the compiler infer the generic type info for you, as illustrated in the following piece of code (C# 3.0):

    using System;

    class Program
       static void Main()
          Bar bar = new Bar();

          bar.Foo = new Foo();
          bar.Foo.Bar = new Bar();
          bar.Foo.Bar.Foo = new Foo();

          Foo foo = bar.IsNull(b => b.Foo).IsNull(f => f.Bar).IsNull(b => b.Foo);
          Console.WriteLine(foo == null);

    class Bar
       public Foo Foo {get;set;}

    class Foo
       public Bar Bar {get;set;}

    public static class ObjectExtension
       public static R IsNull<T,R>(this T value, Func<T,R> func)
          where T : class
          return value == null ? default(R) : func(value);

    It's not as easy as some kind of proposed ?. operator but it could serve as a workaround, especially when writing query expressions. All it's doing is shortcutting a clumsy nesting of ? : operator uses:

    Foo foo = bar != null ? (bar.Foo != null ? (bar.Foo.Bar != null ? (bar.Foo.Bar.Foo != null ? bar.Foo.Bar.Foo : null) : null) : null) : null;

    Concerning the ?. operator I do recognize the value as well but I feel it's a bit too late in the Orcas release cycle to design and implement this properly, especially to make it consistent when used in combination with properties and fields, indexers, method invocations, etc, as well as tools functionality such as IntelliSense.