Setter and Getter in CSharp
This CSharp tutorial is about setters and getters.
As already discussed in one of the last articles, we can access the functions of a class B from a class A, if they are declared public. Now we will make use of this to get class B variables from class A, to overwrite them and thus to set them. To achieve this, we must use setters and getters.
Basic setter function
private variableType VariableName1;
public void setVariableName1(variableTyp variableName2){
variableName1=variableName2;
}
By adding private before the data types, this variable is only visible in the same class in which it was created. In addition, we say that the setter function is public, and has void as its return value. The function we call set + the variable name.
Within the curly brackets, we create a variable of the same data type as the variable to be set.
In the braces we now define that the variable we have created as private is equal to the variable in our curly brackets.
A concrete example:
public class ClassA {
private string name;
public void setName(string myName){
name= myName;
}
}
As we can see here, we have created the variable name outside a function, thus it is global.
Now we can set the variable from class B, but we can not show it there. To achieve this, we have to add a getter to our class A.
public dataType getVariableName1(){
return variableName1;
}
For a getter function, it is important that the data type is corresponding to the type of the variable that we want to get delivered. So in the body, so inside the {}, we just have a return and the name of the variable that the function should return.
Example of a getter function in CSharp
public string getName(){
return name;
}
In order to see the changes within our variable we write it onto the console.
Console.WriteLine("Your name is: " + classAObject.getName());
Now class B:
class KlasseB
{
public static void Main(string[] args)
{
ClassA classAObject = new KlasseA();
Console.WriteLine("Who is your boss?");
string input = Console.ReadLine();
classAObject.setName(input);
Console.WriteLine("Your bosses name is " + classAObject.getName());
Console.ReadLine();
}
}
}
In ClassB, we create an object of ClassA classAobject. Then we ask the user for the name of his boss and save it in the input variable, which we send to the object via Setter (setName ()). And then we show the name.
So now we have seen how Setter & Getter work in CSharp and how to use them.