Search code examples
c#propertiesgetsetaccessor

I need someone to correct my thinking on C# Properties (get & set)


I am having a hard time understanding how properties are "connected" to backing fields. I've set up a common example. I often see get and set simplified to {get; set;}. Is this only appropriate when one field is present or can it still work with two same-type fields. If it does work, is the name property in this code acting on behalf of name or address or both? I'm having a hard time understanding the importance of the private field if the information that would be stored there is stored/accessed in a public property. Is that making sense?

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      Person myObj = new Person();
      myObj.Name = "Liam";
      Console.WriteLine(myObj.Name);
    }
  }
  class Person
  {
    private string name;
    private string address; 
    public string Name {get; set;}  
  }
  
}

Solution

  • You don't need properties with backing fields. Particularly if they are publicly read-able and write-able.

    No backing fields

    There are a number of options without backing fields.

    Public setters and getters

    // inline value initialisation
    var p1 = new Person()
    {
        Name = "John"
    };
    
    // instantiation + setting
    var p2 = new Person();
    p2.Name = "John";
    
    class Person
    {
        public string Name {get; set;}  
    }
    

    Public getters, private setters

    // inline value initialisation
    var p1 = new Person("John");
    
    class Person
    {
        public string Name {get; private set;} 
    
        public Person(string name)
        {
            this.Name = name;
        }
    }
    

    Or ...

    // inline value initialisation
    var p1 = new Person();
    p1.SetSomeProps("John");
    
    class Person
    {
        public string Name {get; private set;} 
    
        public void SetSomeProps(string name)
        {
            this.Name = name;
        }
    }
    

    With backing fields

    // inline value initialisation
    var p1 = new Person()
    {
        Name = "John"
    };
    
    // instantiation + setting
    var p2 = new Person();
    p2.Name = "John";
    
    class Person
    {
        private string theName = string.Empty;
    
        public string Name
        {
            get
            {
                return this.theName;
            }
    
            set(string value)
            {
                this.theName = value;
            }
    
        }  
    }