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;
} 
4
  • 3
    That's complete nonsense and trivially provable as nonsense by inspecting the generated code of a function that uses ?..
    – user743382
    Sep 11, 2016 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, 2016 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, 2016 at 10:49
  • It is nonsense. Read that article. filipekberg.se/2015/01/11/csharp-6-0-null-propagation Sep 11, 2016 at 10:50

1 Answer 1

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;
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.