Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
Can somebody help me understand the get & set ? Why are they needed?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Warning: I am assuming you already know about object-oriented programming.
What are properties?
Properties are language elements that allow you to avoid the repetitive
getXYZ()accessors andsetXYZ()mutators techniques found in other languages, like Java.Why do they exist?
They aim to solve the following problems:
Saying
getandsetin the beginning of every access or mutation of a value is annoying and distracting.In Java, you often say:
and then consistently say:
After a while, the
getandsetbecome rather annoying.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:
Return the current value of the property. Oftentimes, this is nothing more than something like the following:
Set the value of the property:
Other notes:
Auto-implemented Properties
C# 3.0 introduced auto-implemented properties:
This is equivalent to:
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:
You then use them like
obj[5] = 10;, which is equivalent to calling thesetmethod ofobj‘s indexer.In fact,
System.Collections.Generic.List<T>is indexed:Isn’t that neat? 🙂
Anything else?
There are many more features to properties, not all of which are available in C#: