Skip to main content

What is the purpose of accessors?

Can somebody help me understand the get & setWhy are they needed? I can just make a public variable.



What are properties?

Properties are language elements that allow you to avoid the repetitive getXYZ() accessors and setXYZ() mutators techniques found in other languages, like Java.

Why do they exist?

They aim to solve the following problems:
  1. Saying get and set in the beginning of every access or mutation of a value is annoying and distracting.
    In Java, you often say:
    class person
    {
        private int _age;
        public void setAge(int value) { /*check value first, then set _age*/ }
        public int getAge() { return this._age; }
    }
    and then consistently say:
    if (person.getAge() > blah || person.getAge() < 10)
    {
        person.setAge(5);
    }
    After a while, the get and set become rather annoying.
  2. Providing direct access to the actual variable breaks encapsulation, so that's not an option.

How are they used?

They are used just like variables. You read/write to them just like variables.

How are they created?

They are created as methods. You define a pair of methods that:
  1. Return the current value of the property. Oftentimes, this is nothing more than something like the following:
    class Person
    {
        private int _age; //Declare the backing field
    
        public int Age
        {
            get { return this._age; }
            set { ... }
        }
    }
  2. Set the value of the property:
    class Person
    {
        public int Age
        {
            get { ... }
            set
            {
                if (value < 0) //'value' is what the user provided
                { throw new ArgumentOutOfRangeException(); } //Check validity
                this._age = value;
            }
        }
    }

Other notes:

Auto-implemented Properties

C# 3.0 introduced auto-implemented properties:
public int Age { get; set; }
This is equivalent to:
private int _age; //The name is auto-generated
public int Age { get { return this._age; } set { this._age = value; } }
Why does it exist?
It helps you avoiding breaking changes in client executables.
Let's say you're lazy and don't want to type the whole thing, and decide to expose a variable publicly. You then create an executable that reads from or writes to that field. Then you change your mind and decide that you in fact needed a property, so you change it to one.
What happens?
The depending executable breaks, because the code is no longer valid.
Auto-implemented properties help you avoid that, without extra redundancy in your initial code.

Indexers

Indexers extend the property syntax to let you index objects (surprise!), just like arrays.
For C++ users: This is similar to overloading operator [].
Example:
private int[] _elements;

public int this[int index] //Indexed property
{
    get { return this._elements[index]; }
    set
    {
        //Do any checks on the index and value
        this._elements[index] = value;
    }
}
You then use them like obj[5] = 10;, which is equivalent to calling the set method of obj's indexer.
In fact, System.Collections.Generic.List<T> is indexed:
var list = new List<int>();
list.Add(10);
list[0] = 5;  //You're indexing list, as though it were an array!
Isn't that neat? :)

Anything else?

There are many more features to properties, not all of which are available in C#:
  • Parametrized properties, of which indexers are a special kind
  • Getter/setter access modifiers (in C#)
  • Multiple getters or setters (not in C#)
  • Et cetera

Author: Mehrdad


Source: http://stackoverflow.com/questions/6554210/what-is-the-purpose-of-accessors

Comments

Popular posts from this blog

API Security

API Security source:  https://www.apisecuniversity.com/ Tools Kali Linux https://www.kali.org/ $ sudo apt update -y $ sudo apt upgrade -y $ sudo apt dist-upgrade -y $ sudo apt autoremove -y Passive API Reconnaissance Google Dorking Finds all publicly available WordPress API user directories. inurl:"/wp-json/wp/v2/users" Finds publicly available API key files. intitle:"index.of" intext:"api.txt" Finds potentially interesting API directories. inurl:"/api/v1" intext:"index of /" Finds all sites with a XenAPI SQL injection vulnerability. (This query was posted in 2016; four years later, there are currently 141,000 results.) ext:php inurl:"api.php?action=" This is one of my favorite queries. It lists potentially exposed API keys. intitle:"index of" api_key OR "api key" OR apiKey -pool GitDorking filename:swagger.json extension: .json TruffleHog $ sudo docker run -it -v "$PWD:/pwd" trufflesecurity/truf

XML Webservice (ASMX) - SOAP Request and Response Invocation logging

You are an integration developer. Eventualy you came into the state where there is nothing else you can debug, and you have to check which SOAP request it is built on the request, and which SOAP response you are getting from the server. C# XML Webservice (ASMX) - SOAP Request and Response Invocation logging In the legaccy .NET framework System.Web.Services , this means using soapExtensions to help you intersept the interaction with the webservice. This is done like so:  public class TraceExtension : SoapExtension     {         Stream oldStream;         Stream newStream;         string filename;         // Save the Stream representing the SOAP request or SOAP response into          // a local memory buffer.          public override Stream ChainStream(Stream stream)         {             oldStream = stream;             newStream = new MemoryStream();             return newStream;         }         // When the SOAP extension is accessed for the first time, the XML Web

Agile Leadership

Agile LeaderShip Reference: IPMA Reference Guide ICB4 in an Agile World https://www.ipma.world/news/ipma-reference-guide-icb4-agile-world/ 1. Perspective 1.1 Strategy Description: Change Blurred vision Agile strategy Emergent Create and adapt Giving meaning to work Key Competence Indicators Align agile teams with the organisational mission and vision Identify and exploit opportunities to influence organisational strategy Develop and ensure the ongoing validity of the business/organisational justification Determine, assess, and review critical success factors Determine, assess, and review key performance indicators Examples of Measures Reflects the mission and vision of the organisation Identifies new opportunities and threats which could alter the strategy Uses the CSFs for managing stakeholders Uses information systems for strategic performance 1.2 Governance, structures, and processes Description: Challenges Lean organisation Customer value Agile working Different structures Key Comp