1

Recently I heard oppinion that C# null-safe navigator (?.) has influence on performance due to implementation via try - catch. It's very hard to belive that ?. only wrapper like below but I can't find any proof about it.

try
{
...
}
catch (NullReferenceException)
{
return null;
} 
Ilya Sulimanov
  • 7,636
  • 6
  • 47
  • 68
  • 3
    That's complete nonsense and trivially provable as nonsense by inspecting the generated code of a function that uses `?.`. –  Sep 11 '16 at 10:48
  • I don't see why anyone would not implement that using a simple if/else construct. You got a source for the exception idea? – Timbo Sep 11 '16 at 10:49
  • You could dig into it by just writing both the implicit version via `.?` and the assumed explicit version and look into the IL code with something like ILSpy or ildasm – DAXaholic Sep 11 '16 at 10:49
  • It is nonsense. Read that article. http://www.filipekberg.se/2015/01/11/csharp-6-0-null-propagation/ – Farhad Jabiyev Sep 11 '16 at 10:50

1 Answers1

2

This is absolutetly not true. It is simply an if-else statement. Try it out using Roslyn and check what the compiler generates

Your Code:

public class C 
{
    public void M() 
    {
        C c = new C();

        int? result = c?.SomeMethod();

        Console.WriteLine(result);
    }

    public int SomeMethod()
    {
        return 1;
    }
}

Generated Compiler Code:

public class C
{
    public void M()
    {
        C c = new C();
        int? num = c != null ? new int?(c.SomeMethod()) : null;
        Console.WriteLine(num);
    }
    public int SomeMethod()
    {
        return 1;
    }
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63