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

前端 未结 7 2030
醉梦人生
醉梦人生 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 _next = Next();
    
        public MyClass()
        {
            this._next.MoveNext();
        }
    
        public string MyName
        {
            get
            {
                var n = this._next.Current;
                this._next.MoveNext();
                return n;
            }
        }
    
    
        public static IEnumerator 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.

提交回复
热议问题