I am having trouble understanding the concept of getters and setters in the C# language. In languages like Objective-C, they seem an integral part of the system, bu
Most languages do it this way, and you can do it in C# too.
public void setRAM(int RAM)
{
this.RAM = RAM;
}
public int getRAM()
{
return this.RAM;
}
But C# also gives a more elegant solution to this :
public class Computer
{
int ram;
public int RAM
{
get
{
return ram;
}
set
{
ram = value; // value is a reserved word and it is a variable that holds the input that is given to ram ( like in the example below )
}
}
}
And later access it with.
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;
For newer versions of C# it's even better :
public class Computer
{
public int RAM { get; set; }
}
and later :
Computer comp = new Computer();
comp.RAM = 1024;
int var = comp.RAM;