Difference between Properties and Fields

What is the difference between a Field and a Property  C# VB.Net Asp.Net

There is a very significant difference between a field and propoerty within a Class. Clearly both will expose an object's state to the outside world. Object orientated programming principles say that the data is hidden and safe from accidental alteration. Data hiding is the key term describing an Object Oriented Language. That means the internal working of a class should be hidden from the outside world. So, If you expose a member field you are actually exposing the internal implementation of the class. Therefore we wrap fields with Properties to give us the ability to change the implementation without breaking code depending on us. The above statements underlines that properties should be used to define a class's public interface while fields are meant to be used in the private, internal workings of a class.

Properties vs Fields


A field is a variable that is declared directly in a class or struct. Generally, developers should use fields only for variables that have private or protected accessibility. Fields should (most of the time) be kept private to a class and accessed via get and set properties.


C# Properties vs Fields

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties expose fields, that means it enable a class to expose a public way of getting and setting values, while hiding implementation. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.


Difference between Properties and Fields c#

Properties have the primary advantage of allowing you to change the way data on an object is accessed without breaking it's public interface. Properties may run for a very long time and may even throw exceptions. Fields are fast and will never throw exceptions. Properties may return a different value for each call but Fields always return the same value (except the issue with multiple threads) For ex: A property such as DateTime.Now is not always equal to itself. More over, you can use properties for data-binding and work with xml-serialization.
 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About