call instead of callvirt in case of the new c# 6 “?” null check

前端 未结 3 1739
后悔当初
后悔当初 2021-02-19 06:17

Given the two methods:

    static void M1(Person p)
    {
        if (p != null)
        {
            var p1 = p.Name;
        }
    }

    static void M2(Perso         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-19 07:16

    I think it's clearly now,

    This is an easy and thread-safe way to check for null before you trigger an event. The reason it’s thread-safe is that the feature evaluates the left-hand side only once, and keeps it in a temporary variable. MSDN

    So it is safe to use call instruction here.

    I wrote a blog post about the differences between call and callvirt and why C# generate callvirt

    Thanks Dan Lyons for the MSDN link.

提交回复
热议问题