Conteúdo do Curso
C# Beyond Basics
C# Beyond Basics
Correctly Accessing Fields in Struct Methods
So for we created methods, passed data into them and used them with no issues but consider an example where the name of the method parameter clashes with the name of a field inside the structure:
index
using System; struct Coordinate { public int x; public int y; public void setValue(int x, int y) { x = x; y = y; } public void displayValue() { Console.WriteLine($"({x}, {y})"); } } class ConsoleApp { static void Main(string[] args) { Coordinate coord = new Coordinate(); coord.setValue(5, 7); coord.displayValue(); } }
The compiler doesn't show any error in this case however the program is logically incorrect as the the output of the program shows (0, 0)
even though we used setValue(5, 7)
.
This is because the statement x = x
is very ambiguous as both the method parameter and the struct field have the name x
.According to the compiler, in the statement x = x
the method parameter x
assigns the value x
to itself again, which is logically a null statement and hence doesn't do anything.
To fix this we use the this
keyword. this
keyword tells the compiler that we are referring to the field of the struct.
The syntax is this.fieldName
. So the fixed code will look like:
index
using System; struct Coordinate { public int x; public int y; public void setValue(int x, int y) { this.x = x; this.y = y; } public void displayValue() { Console.WriteLine($"({x}, {y})"); } } class ConsoleApp { static void Main(string[] args) { Coordinate coord = new Coordinate(); coord.setValue(5, 7); coord.displayValue(); } }
Now the compiler knows that in the statement x = x
, the x
on the left side is a struct field while x
on the right side a method parameter, and hence the field is successfully updated this time.
We use this
keyword to solve wherever there is any ambiguity in code. It is generally a good practice to always use this
keyword when accessing fields in struct methods.
Obrigado pelo seu feedback!