What is the difference between a property and a field in C#

Difference between Field and Property in C#

Fields are variables of any type declared directly in class; Properties are pro versions of fields with additional capabilities of get and set. Find a detailed article about Fields and Properties in C# here- Fields and Properties in C#.

  • Different access levels Get, Set, Init, and Required - Using properties, we can play by making them either read-only write only or limiting them to just object initialization, fields do not give us these facilities. The required keyword works both.
  • Access Modifier - Generally, fields are kept private, and properties are public, but that's not the rule although.
  • Abstractions - Properties are used to add an additional layer before accessing the information directly, so through properties, we can abstract data while fields are accessed directly (if public)
  • Working With Interfaces - If we are working with interfaces, then we are allowed to have properties in the interface, but field instance is not allowed.
  • Property Changed - Via properties, we can get notified when property changes using INotifyPropertyChanged, but we can not do this with fields
  • Conditional Values | Validation - We can apply rules or validations on properties, but the field does not support this.
  • Data Binding - Properties are used for data binding as well, while fields cannot.
  • Naming Convention -  Fields are typically named with a lowercase letter, while properties are typically named with an uppercase letter
  • Attributes - We can put attributes over both properties and fields, e.g., Description, Default Value, etc.

Fields

        public class Students
        {
            public int Id;
            public int RollNo;
            public string Name = "";
        }

Properties

        public class StudentsProperties
        {
            private int _age;
            private string _name = "";
            public int Id { get; set; }
            public string Name
            {
                get
                {
                    return _name;
                }
                set
                {
                    _name = value;
                }
            }
            public int Age
            {
                get
                {
                    return _age;
                }
            }
        }

Reference