Are these two lines the same, '? … :' vs '??'?

前端 未结 7 2027
醉梦人生
醉梦人生 2021-01-30 19:28

Is there a difference between these two lines?

MyName = (s.MyName == null) ? string.Empty : s.MyName

or

MyName = s.MyName ?? st         


        
相关标签:
7条回答
  • 2021-01-30 20:19

    If the property is more than a simple getter, you might be executing a function twice in the non-null case for the first one.

    If the property is in a stateful object, then the second call to the property might return a different result:

    class MyClass
    {
        private IEnumerator<string> _next = Next();
    
        public MyClass()
        {
            this._next.MoveNext();
        }
    
        public string MyName
        {
            get
            {
                var n = this._next.Current;
                this._next.MoveNext();
                return n;
            }
        }
    
    
        public static IEnumerator<string> Next()
        {
            yield return "foo";
            yield return "bar";
        }
    }
    

    Also, in the non-string case, the class might overload == to do something different than the ternary operator. I don't believe that the ternary operator can be overloaded.

    0 讨论(0)
提交回复
热议问题