UPDATE: I wrote a blog post that discusses this topic in more detail. http://www.codeducky.org/properties-fields-and-methods-oh-my/
They usually return the same result. However, there are several cases where you notice noticeable differences when MyName is a property, as the MyName getter will be executed twice in the first example and only once in the second example.
For example, you may encounter performance differences from executing MyName twice:
string MyName { get { Thread.Sleep(10000); return "HELLO"; } }
Or you may get different results when running MyName twice if MyName has the status:
private bool _MyNameHasBeenRead = false; string MyName { get { if(_MyNameHasBeenRead) throw new Exception("Can't read MyName twice"); _MyNameHasBeenRead = true; Thread.Sleep(10000); return "HELLO"; } }
Or you can get different results from executing MyName twice if MyName can be changed in another thread:
void ChangeMyNameAsync() { //MyName set to null in another thread which makes it //possible for the first example to return null Task.Run(() => this.MyName = null); } string MyName { get; set; }
Here's how the actual code is compiled. First a piece with a triple expression:
IL_0007: ldloc.0
and here is a piece with a zero coalescing operator:
IL_0007: ldloc.0
As you can see, the compiled code for the ternary operator will make two calls to get the value of the property, while the operator with zero coalescing will only do 1.
Steven Wexler Jan 10 '14 at 19:12 2014-01-10 19:12
source share