What is backing field?

Oleh Lutsenko 4 days ago

Ok, in OOP languages like C# we have classes. Classes provides us an abstraction mechanism and also encapsulation. Encapsulation means we hide from outside some internal implementation details
We control it via access modifiers, e.g. private, protected, public.

Let’s say we have a class ResistanceBase which has some geo location

public class ResistanceBase 
   {        
        public GeoLocation Location;
   }

if we create then an instance of ResistanceBase then someone from outside will be able to set value to our Location

var ourBase = new ResistanceBase();
ourBase.Location = new GeoLocation();

this is not cool, because most probably in many cases we do not want outsiders set values to fields of our class, but we want them to be able to read our location, so what can we do? (edited)

In Java and early versions of C# that was solved by creating methods. If we want to just let read the value of our field we can provide a Read method (or Get)

public class ResistanceBase 
   {
       private GeoLocation _location;       
       public GeoLocation GetLocation() {
           return _location;
        }
   }

sometimes we want also to allow set value for our classes fields, that can be solved by Set method, e.g.

public class ResistanceBase
    {
        private GeoLocation _location;
        public GeoLocation GetLocation() {
            return _location;
        }        public void SetLocation(GeoLocation location) {
            _location = location;
        }
   }

If I am not mistaken, Java developers still continue on that path, but C# designers decided, hey, this pattern of having a private field and two methods with some access modifiers - one for get value and another for set value - is so common, why don’t we basically provide a language level syntactic sugar and hence a concept of properties was born.

public class ResistanceBase 
    {
        public GeoLocation Location { get; set; }
    }

“Syntactic sugar” - is basically additionally abstracted code at the language level which is made for the sake of making it easier to read, write and basically express thoughts, which later will be handled by the compiler

so, in that last example that line:

public GeoLocation Location { get; set; }

literally compiled, interpreted as

private GeoLocation _location;
        public GeoLocation Location 
        { 
            get 
            {
               return _location;
           } 
           set 
            {
                _location = value;
            } 
        }

basically two methods and BACKING private field.