This in CSharp
There is a term in programming which often makes some difficulties for beginners. This term actually means only this and that is used in programming to make it clear that the variable is the variable of the context or the class and not the variable of the function e.g.
In our setter and getter tutorial we had learned that a setter looks like this:
public class ClassB {
private string name;
public void setName(string myName){
name=myName;
}
}
But you can also do the following:
Example for This in Setters in CSharp
public class ClassB {
private string name="Chuck Norris";
public void setName(string name){
this.name=name; //e.g. changed via ClassA.setName("Eminem")
}
}
This is used here to say this.name, which is the global variable name, is the name we get as a parameter. If we were not using this here, the global string variable name would not be changed despite calling the function setName.
CSharp considers the parameter variables first. So if we want to change the global variables and the variable names that we create in our function as parameters have the same name as the global variables, we need to make CSharp clear that we want to assign a value to the variable in the function, And not those we have initialized globally.
This is when passing instances to an object
This is also used when you want to pass an object to the instance of the class in which the object was created. It will look like that:
object.itsme(this);
This at Constructors
this can also be used with constructors. So let’s say you give the global variable and the constructor argument the same name. And now if you use e.g.
name = name in a constructor, or generally, there is no real added value because you do not know which name is meant (the global variable or the constructor argument)
this.name = name can be used to set the variable name of the class (so the global), with the name given as a parameter.