C# this Reference
In this chapter you will learn:
- What is C# this Reference
- Example for this Reference
- How to use this keyword to avoid name hiding
- Invoke a constructor through this
Description
The this
reference refers to the instance itself.
The this
reference is valid only within nonstatic members of a class or struct.
Example
Example for this Reference
using System;//from ww w .j ava2 s . c o m
class Rectangle {
public int Width;
public int Height;
public Rectangle(int w = 5, int h = 6){
this.Width = w;
this.Height = h;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
Console.WriteLine(r.Height);
}
}
The output:
this and name shading
this can be used to avoid name shading.
using System;/*w ww.j a v a2 s . c o m*/
class Rectangle {
public int Width;
public int Height;
public Rectangle(int Width, int Height){
this.Width = Width;
this.Height = Height;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(2,3);
Console.WriteLine(r.Width);
Console.WriteLine(r.Height);
}
}
The output:
this cannot be used in static context.
this calls constructors
The general form using this
to call constructors is shown here:
constructor-name(parameter-list1) : this(parameter-list2) {
// ... body of constructor, which may be empty
}
The following code shows how to use this
keyword to call constructors.
using System; //from www .j a v a2 s. com
class XYCoord {
public int x, y;
public XYCoord() : this(0, 0) {
Console.WriteLine("Inside XYCoord()");
}
public XYCoord(XYCoord obj) : this(obj.x, obj.y) {
Console.WriteLine("Inside XYCoord(obj)");
}
public XYCoord(int i, int j) {
Console.WriteLine("Inside XYCoord(int, int)");
x = i;
y = j;
}
}
class MainClass {
public static void Main() {
XYCoord t1 = new XYCoord();
XYCoord t2 = new XYCoord(8, 9);
XYCoord t3 = new XYCoord(t2);
Console.WriteLine("t1.x, t1.y: " + t1.x + ", " + t1.y);
Console.WriteLine("t2.x, t2.y: " + t2.x + ", " + t2.y);
Console.WriteLine("t3.x, t3.y: " + t3.x + ", " + t3.y);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: