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

- 20,711
- 12
- 68
- 90
-
6What's with the rampant down voting? – Jason Towne Jul 02 '11 at 00:02
-
2@Jason: i think this is because people improve their answers and (my assumption) because dissenting opinions collide and other correct the downvotes later. – Tim Schmelter Jul 02 '11 at 00:08
-
@Tim I +1'd your comment. I got some serious down votes as I was refining my answer. – Chase Florell Jul 02 '11 at 00:10
-
If nothing else, @Ken got a pretty canonical definition of `get; set;` accessors. – Chase Florell Jul 02 '11 at 00:18
-
1@rock: that depends on the meaning of "newcomer". Maybe he needs a more exhausting answer on the basics of OO. – Tim Schmelter Jul 02 '11 at 00:21
-
@Tim - no argument from me there. – Chase Florell Jul 02 '11 at 00:39
-
"Yahoo! Answers" .... isn't that like "Fox News"? (Why yes, yes it is.) – Jul 02 '11 at 05:52
-
To answer your edited question, I would ask you to read up on encapsulation. It's a mechanism in place to avoid unwarranted access to your variables. But if you don't require any error checking, value modification, or computation before accessing or mutating a variable, and don't have any restrictions (public, protected, or private) on who can access and mutate your variable, then by all means, you can just make the variable public. – K Mehta Jul 03 '11 at 00:34
6 Answers
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 and setXYZ()
mutators techniques found in other languages, like Java.
Why do they exist?
They aim to solve the following problems:
Saying
get
andset
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
andset
become 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:
class Person { private int _age; //Declare the backing field public int Age { get { return this._age; } set { ... } } }
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

- 205,094
- 128
- 528
- 886
-
2it's funny, every single answer that got any up votes, also go down votes. :-s – Chase Florell Jul 02 '11 at 00:12
-
@rockinthesixstring: Thanks. :) I was a little busy when I was writing the original answer so I didn't have time for a full explanation... glad this one's better. – user541686 Jul 02 '11 at 00:36
-
Thanks for the answer, but why should I use get{} and set{}, instead just using the '=' operator? – MasterMastic Jul 02 '11 at 04:55
-
@Ken: You *create* (i.e. *define*) properties with `get` and `set`. You *use* them with `=`. They don't substitute for each other. – user541686 Jul 02 '11 at 05:10
-
-
-
@Mehrdad: Sure. make a class, and instead making the var private, just make it public from the begning, because you'll get access to it through the `get` and `set` anyways. and than just use: `myVar = 43;`, for example. – MasterMastic Jul 02 '11 at 06:01
-
@Ken: Ah... This goes back directly to my **Warning** at the beginning; it has to do with [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)). Try reading up on the concepts of OOP and *then* reading about Properties in C#, and it'll make more sense. – user541686 Jul 02 '11 at 06:09
-
@Mehrdad oh im so sorry I missed it. :( If I may ask a question before I started reading, if that's ok, I understand it for security reasons, but who am I securing those vars from? The user? I just won't put any input for it. The programmer? well, he'll just change it to public. how hard can it be to replace a word, right? not very high security. – MasterMastic Jul 02 '11 at 06:14
-
@Ken: There are two reasons: 1. It's usually **not** for security, but it's rather a *contract* that you set with yourself (and anyone else who uses the code) that you both agree upon. You don't *have* to do it, but over time, programmers have come to the realization that encapsulation and abstraction are *excellent* ideas. (E.g.: You probably don't know or care how your car works, and yet you drive it. *Can* you mess with the engine? Probably. *Do* you? Probably not. Same idea here.) Reason 2: There actually *is* some security if e.g. you're giving a signed binary: it can't be tampered with! – user541686 Jul 02 '11 at 06:43
-
@Mehrdad For the first reason: But I still change the value. _sorry for taking so much of your time :(_ – MasterMastic Jul 02 '11 at 07:33
-
3@Ken: Don't worry about my time, if we didn't want to answer we wouldn't be on this site. :) Yes, you still change the value. But you can *perform arbitrary checks* on the value when you use a property, when you don't have *any* control over what happens when you expose a field. That's a big difference. – user541686 Jul 02 '11 at 07:36
-
what do you mean by "executable that reads from or writes to that field"? Do you mean a separate program in run time can read/write a public field but cannot read/write a public property? I do not get this part.. if I make a change I just recompile my code... Would you provide a simple example? – KMC Sep 20 '16 at 11:24
-
"Providing direct access to the actual variable breaks encapsulation, so that's not an option." It's still not clear to me from reading this answer why this is a bad thing. If different people create different instances of a class, then "exposing" the variable isn't going to give up any additional information, no? Say Client1.exe creates a Person object (with a public "age" variable.) Client2.exe also uses the Person class. How is Client2.exe going to know or care about the age of the Person in Client1.exe? – Lou Jan 15 '21 at 11:18
-
@Lou: This isn't about executables—but I didn't really try to explain encapsulation here. It goes back to the first sentence in my answer—namely, it assumes you already understand & accept the premises of OOP (such as the idea that encapsulation is a "good thing"). In other words, the assumption is that you would already want to do `getAge()` and `setAge()` in (say) Java. Your question is: why do that in the first place? Well, one reason is that using a property lets you change (or even remove) the underlying field later needing to modify programs that use it: it abstracts away the field. – user541686 Jan 15 '21 at 11:48
They are called Accessors
The accessor of a property contains the executable statements associated with getting (reading or computing) or setting (writing) the property. The accessor declarations can contain a get accessor, a set accessor, or both. The body of the get accessor resembles that of a method. It must return a value of the property type.
http://msdn.microsoft.com/en-us/library/w86s7x04.aspx
private string m_Name; // the name field
public string Name // the Name property
{
get
{
return m_Name;
}
}
The set accessor resembles a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property.
private m_Name;
public string Name {
get {
return m_Name;
}
set {
m_Name = value;
}
}
Then in the incarnation of C# 3, you can do this much easier through auto-properties
public string Name {get; set; } // read and write
public string Name {get; } // read only
public string Name { get; private set; } //read and parent write

- 46,378
- 57
- 186
- 376
-
-1: Please don't post .NET 1.1 links unless it's a .NET 1.1 question! – John Saunders Jul 01 '11 at 23:54
-
-
@rockin, it's not .NET 3.5 that allows you to do auto-implemented properties, that's a language feature introduced with C# 3. VB did not get that ability until VB10, which runs on .NET 4.0. – Anthony Pegram Jul 01 '11 at 23:58
-
1+1. He effectively answered the question. Getters and Setters are hardly a feature that has changed alot, and he even addressed things that have changed. You need to seriously chill out. – riwalk Jul 01 '11 at 23:59
-
Sorry @Anthony, I'm from the VB world, so yes, I only got to use these in 4.0. I was under the impression that auto-properties came in effect in 3.5 for C#, I've corrected my answer. – Chase Florell Jul 02 '11 at 00:00
-
-
@Mehrdad - [MSDN Says Otherwise](http://msdn.microsoft.com/en-us/library/w86s7x04.aspx) **To the implementer of a class, a property is one or two code blocks, representing a get accessor and/or a set accessor** – Chase Florell Jul 02 '11 at 00:06
-
1@rockinthesixstring: **The documentation is wrong, then.** :( `set` is a **mutator**, not an *accessor* (it's not accessing anything... that makes no logical sense). – user541686 Jul 02 '11 at 00:13
-
`set` is still used to "access" the property, and thereby "mutate" it. I can't mutate a potato into french fries without first having access to the potato. – Chase Florell Jul 02 '11 at 00:16
-
@rockinthesixstring: ... that makes no sense to me whatsoever, sorry. :( – user541686 Jul 02 '11 at 00:23
-
@Stargazer: he edited his answer 12 minutes after my comment. I was commenting on his original answer, which was much shorter and contained almost nothing but an ancient link. Now that he's fixed it, I'm removing the downvote. – John Saunders Jul 02 '11 at 01:46
-
Thanks @John... I actually edited within a minute of my original answer, but it's not recognized as an edit because of StackOverflow's edit threshold. – Chase Florell Jul 02 '11 at 01:48
Properties act as accessors to the internal state of an object, hiding the implementation of that state.
So, for example, you may have a first name property in a class
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
}
}
So anyone using the class doesn't need to know how first name is stored, they just know they can get a string representation of it. By adding a set you also add a mutator, something which changes an objects internal state
public class Example
{
private string firstName;
public string FirstName
{
get {return this.firstName;}
set {set this.firstName = value;}
}
}
Again you're still isolating how the first name is stored internally (encapsulation), but users can change it by passing in a string.

- 55,577
- 12
- 114
- 149
Simply put, get
and set
accessors are the functions called on a Property; that is, when you retrieve the value or when you set it. It forces a type of behavior on the way values are retrieved or set.
For example, you may want to have a mechanism to get/set passwords. Generally speaking, you'll only want to compare the hash of a password instead of storing things plaintext, so you'd have the getter variable retrieve the stored hash, and the setter would take the provided input and hash it for storage.
Here's what I mean:
public class User {
//Usery properties here, and...
private string _password;
public string Password {
get {
return _password;
}
set {
_password = SomeHashingFunction(value);
}
}
}
value
is the variable provided to the setter from what has been given in the variable assignment. e.g.: someuser.Password = "blah";

- 6,153
- 2
- 32
- 47
get{} and set{} are accessors that offer up the ability to easily read and write to private fields. Working with a simple example:
public class Foo()
{
//Field
private int _bar;
//Property
public int Bar
{
get { return _bar; }
set { _bar = value; }
//value is an implicit parameter to the set acccessor.
//When you perform an assignment to the property, the value you
//assign is the value in "value"
}
}
In this case, Bar is a public property that has a getter and a setter that allows access to the private field _bar that would otherwise be inaccessible beyond class Foo.
Now in a class that has an instace of Foo, you can do this:
public class IHasAFoo()
{
private Foo _myFoo = new Foo();
public void SomeMethod()
{
_myFoo.Bar = 42;
}
}
So the public accessor allows you to set the value of the private field back in Foo.
Hope that helps!

- 9,547
- 5
- 45
- 61
-
I'm not the downvoter, but the fields need not be private. The accessors don't even need to access fields. – John Saunders Jul 02 '11 at 01:47
Get and set are used in properties. They can each be public, protected, or private. Similar to accessor and mutator methods, they allow some computation when code tries to access/mutate the property. Of course, as long as you define one of get/set, the other is optional.
Example without properties:
private int test;
public int getTest() {
// some computation on test here, maybe?
return test;
}
private void setTest(int test) {
// some error/range checking, maybe?
this.test = test;
}
With properties:
private int test;
public int Test {
get {
// some computation on test here, maybe?
return test;
}
private set {
// some error/range checking, maybe?
test = value; // value is a keyword here
}
}

- 10,323
- 4
- 46
- 76
-
the only thing I can guess is that you said "similar to accessors and mutators" when they **are** in fact accessors and mutators :-s – Chase Florell Jul 02 '11 at 00:20
-
I would argue that I said similar to access or and mutator methods. I wouldn't consider get and set methods. – K Mehta Jul 02 '11 at 02:33