Using the this Keyword as an Identifier

With C#, you can use the this keyword to identify an object whose code is being executed, which in turn enables you to reference the current object.

You can use the this keyword in a variety of ways. You've already seen how it is used in an indexer. You can also use it as a prefix to a variable identifier to tell the C# compiler that an expression should reference a class field.

For example, consider the Point class in Listing 9-8. Listing 9-8: Fields and Parameters with the Same Name class Point {

public int X; public int Y;

public static void Main() {

public static void Main() {

This code won't behave as expected because the X and Y identifiers are used twice: once as class field identifiers and once in the constructor's parameter list. The code needs to distinguish the field identifier X from the parameter list identifier X. With ambiguous code like this, the C# compiler assumes that the references to X and Y in the constructor statements refer to the parameters, and the code just sets the parameters to the value that they already contain.

You can use the this keyword to differentiate the field identifier from the parameter identifier. Listing 9-9 shows the corrected code with the this keyword used as the prefix for the field name.

Listing 9-9: Using this with Fields class Point {

public int X; public int Y;

public static void Main() {

0 0

Post a comment