Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

properties - Difference between Property and Field in C# 3.0+

I realize that it seems to be a duplicate of What is the difference between a Field and a Property in C#? but my question has a slight difference (from my point of view):

Once I know that

  • I will not use my class with "techniques that only works on properties" and
  • I will not use validation code in the getter/setter.

Is there any difference (except the style/future development ones), like some type of control in setting the property?

Is there any additional difference between:

public string MyString { get; set; }

and

public string myString;

(I am aware that, that the first version requires C# 3.0 or above and that the compiler does create the private fields.)

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fields and properties look the same, but they are not. Properties are methods and as such there are certain things that are not supported for properties, and some things that may happen with properties but never in the case of fields.

Here's a list of differences:

  • Fields can be used as input to out/ref arguments. Properties can not.
  • A field will always yield the same result when called multiple times (if we leave out issues with multiple threads). A property such as DateTime.Now is not always equal to itself.
  • Properties may throw exceptions - fields will never do that.
  • Properties may have side effects or take a really long time to execute. Fields have no side effects and will always be as fast as can be expected for the given type.
  • Properties support different accessibility for getters/setters - fields do not (but fields can be made readonly)
  • When using reflection the properties and fields are treated as different MemberTypes so they are located differently (GetFields vs GetProperties for example)
  • The JIT Compiler may treat property access very differently compared to field access. It may however compile down to identical native code but the scope for difference is there.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...