Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Correctly Accessing Fields in Struct Methods | Structs & Enumerators
C# Beyond Basics
course content

Course Content

C# Beyond Basics

C# Beyond Basics

1. Additional Structures & File Handling
2. Structs & Enumerators
3. Introduction to Object-Oriented Programming (OOP)
4. OOP Essentials
5. OOP Principles

bookCorrectly 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:

cs

index

copy
1234567891011121314151617181920212223242526272829
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:

cs

index

copy
1234567891011121314151617181920212223242526272829
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.

Which keyword is used for eliminating ambiguity when referencing fields inside class methods?

Which keyword is used for eliminating ambiguity when referencing fields inside class methods?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt