Is there a difference between these two lines?
MyName = (s.MyName == null) ? string.Empty : s.MyName
or
MyName = s.MyName ?? string.Empty
Is there a difference between these two lines?
MyName = (s.MyName == null) ? string.Empty : s.MyName
or
MyName = s.MyName ?? string.Empty
UPDATE: I wrote a blog post that discusses this topic in more depth. http://www.codeducky.org/properties-fields-and-methods-oh-my/
Generally they will return the same result. However, there are a few cases where you will experience noticeable differences when
MyName
is a property because theMyName
getter will be executed twice in the first example and only once in the second example.For example, you may experience performance differences from executing
MyName
twice:Or you may get different results from executing
MyName
twice ifMyName
is stateful:Or you may get different results from executing
MyName
twice ifMyName
can be changed on a different thread:Here's how the actual code is compiled. First the piece with the ternary expression:
and here is the piece with the null-coalescing operator:
As you can see the compiled code for the ternary operator will make two calls to get the property value, whereas the null-coalescing operator will only do 1.
Yes, both are the same, and it is the null-coalescing operator.
If we talk about efficiency then
If I use a dissembler then I can see that the first statement needs 19 statements to be executed by the compiler whereas the second statement required only 12 statements to be executed.
No. Both are doing the same thing. Second one is efficient. Which returns the actual value if it is not null. Else the right-hand side value will be returned.
Refer this http://msdn.microsoft.com/en-us/library/ms173224.aspx
Hope this helps.
Yes, they do the same.
??
is shorthand for checking for null.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:
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.
They accomplish the same task.
Only difference would be readability as to whether your coworkers or whomever is reading the code understands the syntax.
EDIT: Additionally the first option can evaluate the property
MyName
twice.