I understand how to create a getters and setters
public myClass
{
public int myVal { get; set; }
// more stuff
}
but I don't understand how to call it later on.
public myOtherClass
{
public myOtherClass()
{
myClass localMyClass = new myClass();
localMyClass.???set??? = 42;
// Intelisense doesn't seem to give any obvious options after I enter
// the period.
}
}
How should I set the value of myVal in localMyClass?
localMyClass.myVal = 42;
Getters and setters let you treat the values like public properties. The difference is, you can do whatever you want inside the functions that do the getting and setting.
Examples:
store other variables
private int _myVal, myOtherVal;
public int MyVal { get; set { _myVal = value; myOtherVal++; } }
make numbers up / return constants
public int MyVal { get { return 99; } set; }
throw away the setter
private int _myVal;
public int MyVal { get { return _myVal; } set { ; } }
In each of these cases, the user will feel like it's just a public data member, and simply type
localMyClass.myVal = 42;
int i = localMyClass.myVal;
The gettors and settors let you make an implementation of your own. Also, as Hogan says, "There are a number of libraries and add-ons [e.g. MVC.NET] that require you to use getter and setter functions" - even if it's for the trivial {get; set;} case.
Set:
localMyClass.myVal = 42
Get:
int variable = localMyClass.myVal;
From the outside, the syntax for accessing getters and setters is indistinguishable from that of accessing variables. Assignments translate into calls of setters, while plain expression uses translate into calls of getters.
In intellisense, the list of getters and setters should open upon placing a dot . after the variable name. Properties should have blue markers to the left of them (as opposed to magenta-colored markers to the left of methods).
You want this
localMyClass.myVal = 42;
to call the setter
and this
varName = localMyClass.myVal;
to call the getter.
Get: var tmp = localMyClass.myVal;
Set: localMyClass.myVal = 2;
Related
Read only properties can be assigned in a constructor. But when I try to explicitly implement get method, compiler shows an error (Property cannot be assigned to -- it is read only.) Can I implement getter or it's supposed to be without implementation?
public class PersonalIncome
{
private decimal _anualRate;
public decimal AnualRate
{
get { return _anualRate != 0 ? _anualRate : 40_000; }
}
public PersonalIncome(decimal paymentRate)
{
switch (paymentRate)
{
case var rate when (rate > 300):
AnualRate = rate; // **Property can not be assigned to -- it is read only.**
break;
default:
break;
}
}
}
You can implement the getter, but then you can only assign values to the backing field directly:
_anualRate = rate;
Once you decide against using the convenience of the auto-property, you have to do everything by yourself.
Your class could be rewritten like this:
public class PersonalIncome
{
public decimal AnualRate { get; private set; }
public PersonalIncome(decimal paymentRate)
{
AnualRate = paymentRate > 300 ? paymentRate : 40_000;
}
}
You refer to a property with a readonly backing-field.
That´s exactly what the compiler also generates from C#6 upwards when using an auto-implemented property with a default-value:
int MyProperty { get; } = -1;
This will be translated to the following:
readonly int _myProperty = -1;
int MyProperty { get { return this._myProperty; } }
Now the compiler replaces every call to your property by the backing-field. However this only works for auto-properties that do not have a body defined. In your case you already have one, which is why the compiler can´t replace that one. As a property itself is nothing but a get- and a set-method, what you want to do is the following, which is obvious non-sense:
int get_MyProperty() { return this._MyProperty; }
...
this.get_MyProperty() = 1;
The reason this works for an auto-property is that the compiler knows how to replace the call to the property. However suppose your own getter was more complex:
get
{
DoSomething();
return this._myProperty + 5;
}
Now the compiler can´t replace the call to the property.
So the only way to have your own get-implementation tigether with a property which is get-only, is to use the backing-field:
this._myProperty = 1;
So after the availability of automatic implementation, and initialization of a property, do I even need a field for my property?
This seems much cleaner:
class A {
public int X {
get;set;
} = 1;
}
Than this:
class A {
int x = 1;
public int X {
get {
return x;
}
set {
x = value;
}
}
}
In the first case, the compiler is already providing a backing field - it's just implicit (and it's given a name that you can't refer to in code). Note that there has to be a backing field in the generated code, as a property itself is really just a pair of methods with some metadata linking them - the presence of a property does not add any state to the object. State is only stored in fields.
It's even cleaner when written on one line - I'd usually see this as:
class A
{
public int X { get; set; } = 1;
}
You dont need a backing field in this situation, but if you want to manipulate the Property with e.g a OnPropertyChanged() then you need to have a backing field
public int X {
get {
return x;
}
set {
x = value;
OnPropertyChanged()
}
}
I am writing following code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReadOnlyObject
{
class Program
{
private readonly int a = 20;
private readonly int b;
public int propa{get;private set;}
public int propb { get; private set; }
public Program(int tmp)
{
b = tmp;
}
static void Main(string[] args)
{
Program obj1 = new Program(30);
Console.WriteLine(obj1.propa); // Console.WriteLine(obj1.a);
Console.WriteLine(obj1.propb); // Console.WriteLine(obj1.b);
Console.Read();
}
}
}
After executing the above i got o/p as follows,
0
0
And when I change the code by replacing two commented statements printing direct member variables I got output as,
20
30
Why is so?
As far I know about properties they are associated with their definition in order the member variables are declared.
You have confusion about auto property, so:
private readonly int a = 20;
private readonly int b;
public int propa{get {return a; }}
public int propb { get {return b;} private set {b = value;} }
now this will print 20, 30
There are two ways to define properties in C#.
The first, the traditional way;
int myProperty;
public int MyProperty
{
get { return myProperty; }
set { myProperty = value; }
}
the second, the auto-property;
public int MyProperty {get;set;}
The first contains a backing variable that you reference in the property accessor. The second implicitly creates a backing variable, because the developers of the language understood that there are a lot of cases where you just need a property!
You can put scope on the auto-property, because you might want to prevent people from setting the value, but internally to the object you should be able to update the value of it.
"As far I know about properties they are associated with their
defination in order the member variables are declated."
Just to clarify all of what you were asking, unless I am reading this statement incorrectly, you're thinking that if you declare variable a and b and the property a and property b that they'll be associated. This is an incorrect assumption.
propa and a are not associated in your example. The compiler is making them auto-implemented properties. http://msdn.microsoft.com/en-us/library/bb384054.aspx If you want propa associated with a then you'd do:
public int propa{get { return a;} }
You're not initializing either property. You also can't set the value of b from a setter if it's marked readonly. You can implement your own 'readonly' type by just not letting the value get set more than once. (Although it doesn't stay true to the constraint that it needs to be initialized in the constructor)
Try this:
private readonly int a = 20;
public int A { get { return a; } }
private int b;
private bool bInitialized = false;
public int B
{
get { return b; }
private set
{
if (bInitialized) return;
bInitialized = true;
b = value;
}
}
The way your code is written propb and propa CANNOT be set outside the scope of the class. so remove the keyword private from the set keyword
if you wrote this.propb = b in your constructor, then I think it should work more like you are expecting.
Can somebody help me understand the get & set?
Why are they needed? I can just make a public variable.
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 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.
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
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
http://msdn.microsoft.com/en-us/library/bb384054.aspx
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.
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";
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
}
}
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!
I"m a little confused with this short hand. Does this allow me to acesss myVar and set myVar like so?
object.myVar = 5;
newNum = object.myVar;
I don't get this.
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
No, what this means is that you have a "hidden" private integer called myVar that nobody outside the class can see, but people from the outside can only see a property called MyProperty, that happens to redirect to myVar, but they won't know it !
from the inside, you can do :
this.myVar = 12;
int test = this.myVar; /*(this. would actually be optionnal)*/
from the outside, if myInstance is an instance of your class, people can do this :
int test = myInstance.MyProperty;
myInstance.MyProperty = 12;
The point of properties is to hide the private members, and control how they are accessed.
It does not allow you, that is the point. You access the private variable via the public property.
In version 3.0 and above you can also do:
public int MyProperty { get; set; }
And access them like so:
object.MyProperty = 5;
newNum = object.MyProperty;
No it won't be redundant
public int MyProperty { get; set;}
This creates a public and a private variable.
Outside classes can command it but there is a hidden private variable that will use the get set method. This is still safe since it is the class itself that will change the values and not some other method from outside.
No it allows you to access your variable myVar by using this:
object.MyProperty = 5;
newNum = object.MyProperty;
you could get rid of the backing variable entirely and do this though:
public int MyProperty
{
get; set;
}
which will still allow you to access your property like the first code section in my answer.
public int MyProperty { get; set; }
wouldn't this be redundant since if MyProperty is public it can already be 'get' and 'set'?